R:将行与测量结果低于特定阈值

时间:2016-02-02 15:25:05

标签: r aggregate

我有一个玩具&#34;包含2列(xy)和8行的数据框。我想合并并汇总y < 10的所有行。合并x的价值不是很重要。

x = c("A","B","C","D","E","F","G","H")
y = c(20,17,16,14,12,9,6,5)

df = data.frame(x,y)
df

    x   y
1   A   20
2   B   17
3   C   16
4   D   14
5   E   12
6   F   9
7   G   6
8   H   5

期望的输出:

    x   y
1   A   20
2   B   17
3   C   16
4   D   14
5   E   12
6   F   20

F不是必需的,可以设置为Other。提前谢谢!

2 个答案:

答案 0 :(得分:2)

我认为这就是你要找的东西。

x = c("A","B","C","D","E","F","G","H")
y = c(20,17,16,14,12,9,6,5)

df = data.frame(x = x[which(y > 10)],y = y[which(y > 10)])
df = rbind(df,data.frame(x = 'f',y = sum(y[which(y < 10)])))

答案 1 :(得分:1)

我们也可以尝试subset/transform/rbind

 rbind(subset( df, y>=10), 
      transform(subset(df, y<10), x= x[1], y= sum(y))[1,])