Calculate row-wise proportions
And another alternative (though this is mostly a pretty version of sweep
)... prop.table
:
> cbind(x[1], prop.table(as.matrix(x[-1]), margin = 1))
id val0 val1 val2
1 a 0.08333333 0.3333333 0.5833333
2 b 0.13333333 0.3333333 0.5333333
3 c 0.16666667 0.3333333 0.5000000
From the "description" section of the help file at ?prop.table
:
This is really
sweep(x, margin, margin.table(x, margin), "/")
for newbies, except that if margin has length zero, then one gets x/sum(x).
So, you can see that underneath, this is really quite similar to @Jilber's solution.
And... it's nice for the R developers to be considerate of us newbies, isn't it? :)
following should do the trick
cbind(id = x[, 1], x[, -1]/rowSums(x[, -1]))
## id val0 val1 val2
## 1 a 0.08333333 0.3333333 0.5833333
## 2 b 0.13333333 0.3333333 0.5333333
## 3 c 0.16666667 0.3333333 0.5000000