确定满足条件的数据点数

时间:2013-08-09 04:04:18

标签: r

如何找出符合特定条件的数据框中的数据点数?

Group<-c("Group 1","Group 1","Group 1","Group 2","Group 2")
Factor<-c("Factor 1", "Factor 1", "Factor 2", "Factor 1", "Factor 2")

data<-data.frame(cbind(Group,Factor))
data

例如,我想知道第1组(因子2)中有多少数据点。 我想我应该可以使用summary函数,但我无法弄清楚如何指定我想要因子级别的组合。例如:

summary(data) #Verifies that Group 1 appears 3 times, and Factor 2 appears twice, but no information on how many times Group 1 AND Factor 2 appear in the same row

那么,如何获得不同因子水平的组合的汇总表?

1 个答案:

答案 0 :(得分:4)

使用逻辑测试,然后使用sum获取特定组合:

sum(with(data,Group=="Group 1" & Factor=="Factor 2"))
[1] 1

要扩展此功能,您只需使用table

即可
with(data,table(Group,Factor))

         Factor
Group     Factor 1 Factor 2
  Group 1        2        1
  Group 2        1        1

...如果你转换回data.frame会给出一个很好的小摘要数据集:

data.frame(with(data,table(Group,Factor)))

    Group   Factor Freq
1 Group 1 Factor 1    2
2 Group 2 Factor 1    1
3 Group 1 Factor 2    1
4 Group 2 Factor 2    1