Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to Convert values to the share of sum of row in dataframe in R?

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?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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])))
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading