Calculate row-wise proportions

自闭症网瘾萝莉.ら 提交于 2019-11-26 19:03:53

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

Another alternative using sweep

sweep(x[,-1], 1, rowSums(x[,-1]), FUN="/")
        val0      val1      val2
1 0.08333333 0.3333333 0.5833333
2 0.13333333 0.3333333 0.5333333
3 0.16666667 0.3333333 0.5000000

The function adorn_percentages() from the janitor package does this:

library(janitor)
x %>% adorn_percentages()
 id       val0      val1      val2
  a 0.08333333 0.3333333 0.5833333
  b 0.13333333 0.3333333 0.5333333
  c 0.16666667 0.3333333 0.5000000

This is equivalent to x %>% adorn_percentages(denominator = "row"), though "row" is the default argument so is not needed in this case. An equivalent call is adorn_percentages(x) if you prefer it without the %>% pipe.

Disclaimer: I created the janitor package, but feel it's appropriate to post this; the function was built to perform exactly this task while making code clearer to read, and the package can be installed from CRAN.

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!