计算逐行比例 [英] Calculate row-wise proportions

查看:180
本文介绍了计算逐行比例的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个数据框:

  x<  -  data.frame(id = letters [1:3] val0 = 1:3,val1 = 4:6,val2 = 7:9)
#id val0 val1 val2
#1 a 1 4 7
#2 b 2 5 8
#3 c 3 6 9

在每行中,我想计算相应的比例(比例)对于每个值。例如。对于列val0中的值,我想要逐行计算val0 /(val0 + val1 + val2)。



期望的输出:

  id val0 val1 val2 
1 a 0.083 0.33 0.583
2 b 0.133 0.33 0.533
3 c 0.167 0.33 0.5

任何人都可以告诉我最好的方法是什么?这里只是三列,但可能有很多列。

解决方案

另外一个选择(虽然这主要是一个漂亮的版本 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

从帮助的说明部分文件在?prop.table


这是真的除了如果margin保持长度为零,那么一个得到x / sum(x) p>

所以,你可以看到,这与@ Jilber的解决方案非常相似。



&p ...而且,R开发人员很高兴认识我们新手,不是吗? :)


I have a data frame:

x <- data.frame(id = letters[1:3], val0 = 1:3, val1 = 4:6, val2 = 7:9)
#   id val0 val1 val2
# 1  a    1    4    7
# 2  b    2    5    8
# 3  c    3    6    9

Within each row, I want to calculate the corresponding proportions (ratio) for each value. E.g. for the value in column "val0", I want to calculate row-wise val0 / (val0 + val1 + val2).

Desired output:

  id     val0  val1   val2
1  a    0.083  0.33   0.583
2  b    0.133  0.33   0.533
3  c    0.167  0.33   0.5

Can anyone tell me what's the best way to do this? Here it's just three columns, but there can be alot of columns.

解决方案

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? :)

这篇关于计算逐行比例的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆