Home > Software design >  How to Convert values to the share of sum of row in dataframe in R?
How to Convert values to the share of sum of row in dataframe in R?

Time:07-22

How can I convert the value of each row to the share sum of row? For instance

df <- data.frame (year  = c("2015", "2016", "2017","2018","2019"),
                  var1 = c(45,45,34,89,55),
                  var2 = c(15,44,33,81,51),
                  var3 = c(12,43,14,29,15)
                  )

  year var1 var2 var3
1 2015   45   15   12
2 2016   45   44   43
3 2017   34   33   14
4 2018   89   81   29
5 2019   55   51   15

Here 45 should be changed by 45/(45 15 12)*100 and so on for the whole data frame?

CodePudding user response:

You can divide each column by rowSums()

df[,-1] <- df[,-1]*100/rowSums(df[,-1])

Output:

  year     var1     var2     var3
1 2015 62.50000 20.83333 16.66667
2 2016 34.09091 33.33333 32.57576
3 2017 41.97531 40.74074 17.28395
4 2018 44.72362 40.70352 14.57286
5 2019 45.45455 42.14876 12.39669

Here is a similar approach using mutate(across()) from dplyr

library(dplyr)
mutate(df, across(-year, ~.x*100/rowSums(df[,-1])))

CodePudding user response:

An option is also with proportions

df[-1] <-  proportions(as.matrix(df[-1]), 1) * 100

-output

> df
  year     var1     var2     var3
1 2015 62.50000 20.83333 16.66667
2 2016 34.09091 33.33333 32.57576
3 2017 41.97531 40.74074 17.28395
4 2018 44.72362 40.70352 14.57286
5 2019 45.45455 42.14876 12.39669
  • Related