Reputation: 2489
I have data that looks like this:
1 55 41 61 73 75 75 84
2 18 29 26 27 24 21 14
3 19 15 18 28 26 16 13
4 26 36 36 42 32 22 21
I would like to divide each row by the total to transform the row into a proportion of total:
mydata[1,]/sum(mydata[1,])
1 0.1185345 0.08836207 0.1314655 0.1573276 0.1616379 0.1616379 0.1810345
...for the whole data set. I can do them individually, how do I do it for all rows?
Upvotes: 2
Views: 1064
Reputation: 9618
Try:
t(apply(df, 1, function(x) x/sum(x)))
V2 V3 V4 V5 V6 V7 V8
[1,] 0.1185345 0.08836207 0.1314655 0.1573276 0.1616379 0.1616379 0.18103448
[2,] 0.1132075 0.18238994 0.1635220 0.1698113 0.1509434 0.1320755 0.08805031
[3,] 0.1407407 0.11111111 0.1333333 0.2074074 0.1925926 0.1185185 0.09629630
[4,] 0.1209302 0.16744186 0.1674419 0.1953488 0.1488372 0.1023256 0.09767442
Or:
sweep(df, 1, rowSums(df), "/")
Upvotes: 4
Reputation: 887291
You can try rowSums
mydata/rowSums(mydata)
# V1 V2 V3 V4 V5 V7 V8
#1 0.1185345 0.08836207 0.1314655 0.1573276 0.1616379 0.1616379 0.18103448
#2 0.1132075 0.18238994 0.1635220 0.1698113 0.1509434 0.1320755 0.08805031
#3 0.1407407 0.11111111 0.1333333 0.2074074 0.1925926 0.1185185 0.09629630
#4 0.1209302 0.16744186 0.1674419 0.1953488 0.1488372 0.1023256 0.09767442
Upvotes: 5