我有一个玩具"包含2列(x
和y
)和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
。提前谢谢!
答案 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,])