[SOLVED] 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:

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


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

Answered By – langtang

Answer Checked By – Robin (BugsFixing Admin)

Leave a Reply

Your email address will not be published. Required fields are marked *