-1

I would like to create a new column in my dataset that shows the difference in the values (column b in example dataset) between the current row and the first row within a group (column a in example dataset) in R. How would I go about doing this?

a<-c(1,1,1,1,2,2,2,2)
b<-c(2,4,6,8,10,12,14,16)

have<-as.data.frame(cbind(a,b))

> have
a  b
1  2
1  4
1  6
1  8
2 10
2 12
2 14
2 16

> want
a  b c
1  2 0
1  4 2
1  6 4
1  8 6
2 10 0
2 12 2
2 14 4
2 16 6
h09812349
  • 109
  • 6

1 Answers1

1

You can use first() to address the first member in the group:

library(dplyr) 
as.data.frame(cbind(a,b)) %>%
group_by(a) %>%
mutate(c = b - first(b)) %>%
ungroup() 
asd-tm
  • 3,381
  • 2
  • 24
  • 41