0

I have this dataframe and I would like to calculate the % for each row (for example). I would like to transform this dataframe in the same dataframe but only for %.

enter image description here

Just like this image:

enter image description here

How Can I do it?

Data:

dat <- data.frame(
  county = c("FRANCIA", "GRECIA", "ITALIA"),
  `310` = c(73, 165, 347),
  `320` = c(13, 80, 118),
  `330` = c(10, 57, 94),
  `340` = c(28, 116, 177),
  check.names = FALSE
)
Sam Firke
  • 21,571
  • 9
  • 87
  • 105
Marcusson
  • 17
  • 4

2 Answers2

0

If you specifically want the % sign included, try adorn_crosstab() from the janitor package:

library(janitor)
dat %>%
  adorn_crosstab(show_n = FALSE, digits = 0)

   county 310 320 330 340
1 FRANCIA 59% 10%  8% 23%
2  GRECIA 39% 19% 14% 28%
3  ITALIA 47% 16% 13% 24%

If you want to retain the proportions as numeric-class, see Calculate row-wise proportions.

(disclaimer: I am the author of this function - but I think it's the fastest way to get to your desired result)

Community
  • 1
  • 1
Sam Firke
  • 21,571
  • 9
  • 87
  • 105
0

Base package, using prop.table. First we convert the data frame to a matrix. Then back to a data frame restoring the column Country using cbind.

cbind(Country = dat[, 1], as.data.frame(prop.table(as.matrix(dat[, 2:5]), 1)))

Output:

  Country       310       320        330       340
1 FRANCIA 0.5887097 0.1048387 0.08064516 0.2258065
2  GRECIA 0.3947368 0.1913876 0.13636364 0.2775120
3  ITALIA 0.4714674 0.1603261 0.12771739 0.2404891
mpalanco
  • 12,960
  • 2
  • 59
  • 67
  • Hi @Marcusson if this or any answer has solved your question please consider [accepting it](http://meta.stackexchange.com/q/5234/179419) by clicking the check-mark. This indicates to the wider community that you've found a solution and gives some reputation to both the answerer and yourself. There is no obligation to do this. – mpalanco Oct 18 '16 at 19:12