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

summing rows of specific columns then dividing by the sum

I am simply trying to sum certain columns in a row and then divide the cells within the row by that sum. And I am wanting to do this in every row. for example, if we take the data set:

lose draw win goals
7 2 5 12
1 2 13 21

We will ignore the goals scored and sum the win, lose and draw columns for the row, then by dividing each cell by the sum value we obtain:

lose draw win goals
7/14 2/14 5/14 12
1/16 2 /16 13/16 21

The code I have tried using is:

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

Df_new <-t(apply(Df, select = c(lose, draw, win), function(x) x/sum(x)))

However, I am getting the error:

Error in match.fun(FUN) : argument "FUN" is missing, with no default

which a google search says I am missing a margin. But I thought that I had specified this by electing the columns.

Thank you

>Solution :

Try this way to specify the column (by sub-setting Df), and then indicating the margin as 1

Df_new = t(apply(Df[,c(1:3)], 1, \(x) x/sum(x)))

       lose      draw       win
[1,] 0.5000 0.1428571 0.3571429
[2,] 0.0625 0.1250000 0.8125000
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