计算具有特定条件的变量

时间:2016-08-04 04:44:59

标签: r

如果事件发生,我会计算,如果发生了事件,它会产生任何后果。我们假设这是我的数据

#mydata

 a   b   c  d  consequence
 0   0   1  1    0
 1   0   1  1    1
 1   1   1  0    0
 0   0   0  1    0

因此,对于每个变量,我计算变量出现的次数以及此变量导致结果的次数:" a"

的示例
  numberofa=length (subset(mydata, mydata$a==1))
  numberofaeffective= Length (subset(mydata, mydata$a==1 $ mydata$consequence=1))

如何编写程序来计算每个变量的这两个指标?

#expected output 

variable  count  count-with-effect
a        2          1
b        1          0
c        3          1
d        3          1

1 个答案:

答案 0 :(得分:1)

我们可以使用sum逻辑向量

来做到这一点
sum(dts$a==1)
#[1] 2

with(dts, sum(a==1 & consequence == 1))
#[1] 1

如果我们需要每个变量(例如' a'到' d')

colSums(dts[1:4] == 1)
# a b c d 
# 2 1 3 3 

和第二个'结果'

colSums(dts[1:4] == 1 & (dts[5] == 1)[row(dts[1:4])])
#a b c d 
#1 0 1 1 

如果我们需要采用特定格式,我们可以gather将数据集summarise变为“长”。格式,然后按操作进行分组,sumlibrary(dplyr) library(tidyr) gather(dts, variable, value, -consequence) %>% group_by(variable) %>% summarise(count = sum(value), count_with_effect = sum(value & consequence)) # variable count count_with_effect # <chr> <int> <int> #1 a 2 1 #2 b 1 0 #3 c 3 1 #4 d 3 1 进行“&#39;值&#39;柱

do {
    b = keypad.getKey();
} while (b = NO_KEY);
相关问题