计算高于阈值的数据帧中的行数作为函数或其他列因子

时间:2016-11-11 09:51:59

标签: r dataframe collapse threshold

我希望找到每个主题的行数,其中每个主题的值大于11,并将其输出到数据框中进行分析。数据集很大(5000行),因此需要一个函数。

subject = c(rep("A", 12), rep("B", 12))        
day = c(1,1,1,1,2,2,2,2,3,3,3,3,1,1,1,1,2,2,2,2,3,3,3,3)
value = c(13,14,15,5,12,9,6,14,4,2,1,2,13,14,15,5,12,9,6,14,2,2,2,3)
df = data.frame(subject, day, value)
df

   subject day value
1        A   1    13
2        A   1    14
3        A   1    15
4        A   1     5
5        A   2    12
6        A   2     9
7        A   2     6
8        A   2    14
9        A   3     4
10       A   3     2
11       A   3     1
12       A   3     2
13       B   1    13
14       B   1    14
15       B   1    15
16       B   1     5
17       B   2    12
18       B   2     9
19       B   2     6
20       B   2    14
21       B   3     2
22       B   3     2
23       B   3     2
24       B   3     3

我想要的输出是

subject.agg = c(rep("A", 3), rep("B", 3)) 
day.agg = as.factor(c(1,2,3,1,2,3))
highvalues = (c(3,2,0,3,2,0))
df.agg = data.frame(subject.agg,day.agg,highvalues)
df.agg

  subject.agg day.agg highvalues
1           A       1          3
2           A       2          2
3           A       3          0
4           B       1          3
5           B       2          2
6           B       3          0

非常感谢任何帮助。

3 个答案:

答案 0 :(得分:6)

一个选项是来自aggregate

base R
aggregate(cbind(highvalues=value>11)~., df,  sum)

data.table

library(data.table)
setDT(df)[value>11, .(highvalues=.N), by = .(subject, day)]
#     subject day highvalues
#1:       A   1          3
#2:       A   2          2
#3:       A   3          3
#4:       B   1          3
#5:       B   2          2
#6:       B   3          3

答案 1 :(得分:2)

您可以采用tidyverse方式:

df %>%
  filter(value > 11) %>%
  group_by(subject,day) %>%
  mutate(highvalue = n()) %>%
  select(subject, day, highvalue) %>%
  unique()

答案 2 :(得分:1)

library(data.table)
dt = setDT(df)
dt[, sum(value>11),by = .(subject,day)]
   subject day V1
1:       A   1  3
2:       A   2  2
3:       A   3  3
4:       B   1  3
5:       B   2  2
6:       B   3  3