Reputation: 5169
I have a "toy" data frame with 2 columns (x
and y
) and 8 rows. I would like to merge and sum all rows where y < 10
. Value of merged x
is not very important.
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
Desired output:
x y
1 A 20
2 B 17
3 C 16
4 D 14
5 E 12
6 F 20
F
is not necessary and can be set to Other
. Thanks in advance!
Upvotes: 0
Views: 195
Reputation: 886938
We can also try with subset/transform/rbind
rbind(subset( df, y>=10),
transform(subset(df, y<10), x= x[1], y= sum(y))[1,])
Upvotes: 1
Reputation: 561
I think this is what you are looking for.
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)])))
Upvotes: 2