如何在R中满足特定条件的列中对变量求和?

时间:2015-05-21 21:48:52

标签: r

    NoofPreg glu  bp skin  bmi   ped age yes/no
1          6 148  72   35 33.6 0.627  50    Yes
2          1  85  66   29 26.6 0.351  31     No
3          1  89  66   23 28.1 0.167  21     No
4          3  78  50   32 31.0 0.248  26    Yes
5          2 197  70   45 30.5 0.158  53    Yes

我是R的新手,但我无法在网上找到有关如何对R中的数据集执行此类操作的任何说明。 在上面的数据集中,我想总结glu变量,其中yes / no ==“Yes”。这是一个条件总和,为了给出所有glu行的总和,其中yes / no为“Yes”。你会如何在R?

中解决这个问题

非常感谢!

3 个答案:

答案 0 :(得分:2)

试试这个

> with(dat, sum(glu[yes.no=="Yes"]))
[1] 423

dat看起来像这样

> dat
  NoofPreg glu bp skin  bmi   ped age yes.no
1        6 148 72   35 33.6 0.627  50    Yes
2        1  85 66   29 26.6 0.351  31     No
3        1  89 66   23 28.1 0.167  21     No
4        3  78 50   32 31.0 0.248  26    Yes
5        2 197 70   45 30.5 0.158  53    Yes

答案 1 :(得分:0)

试试这个:总和(df $ glu [df $ yes.no ==" YES"])

df是您的数据。

答案 2 :(得分:0)

我认为这是你可以尝试的另一个变种.............

sum(df[df$yes.no=="yes",]$glu)