-1
x <-  c(1,   2,  2,  3,  3, 3,    4)
Fx <- c(.4, .2, .4, .5, .2, 1.2, .8)

So I want to group Fx by values of x and then sum the values in the groups.

It should return:

new_x <-  c(1,   2,     3,         4)
new_Fx <- c(.4, .2+.4, .5+.2+1.2, .8)

How can I do this in r?

1 Answers1

0

This question has been asked before here: How to sum a variable by group?.

With your data, you can try this:

df <-  data.frame(x=c(1,   2,  2,  3,  3, 3,    4), 
                 Fx = c(.4, .2, .4, .5, .2, 1.2, .8))

df$x <- as.character(df$x)

aggregate(df$Fx, by=list(x = df$x), FUN=sum)
AMS Nomad
  • 73
  • 8