If we want to add a column for the sum of a specific condition within a group.
data <- data.frame(id=c(rep(1, 4), rep(2, 3), rep(3, 3), rep(4,4)),
condition=c(1, 1, 0, 0, 1, 1, 0, 1, 1, 0,1,1,0,0),
count=c(1, 2, 0, 0, 1, 2, 0, 1, 2, 0,1,2,0,0),
firstexosure=c(1, 0, 0, 0, 1, 0, 0, 1, 0, 0,1,0,0,0),
outcome=c(0, 0, 0, 1, 0, 0, 1, 0, 0, 1,0,0,1,0),
time=c(100, 250, 220, 300, 240, 380, 150, 200, 320, 360,100,210,220,235) )
data<-data%>%group_by(id,condition)%>%summarise(sum= sum(time))
I would like to add one more column like this.
data <- data.frame(id=c(rep(1, 4), rep(2, 3), rep(3, 3), rep(4,4)),
condition=c(1, 1, 0, 0, 1, 1, 0, 1, 1, 0,1,1,0,0),
count=c(1, 2, 0, 0, 1, 2, 0, 1, 2, 0,1,2,0,0),
firstexosure=c(1, 0, 0, 0, 1, 0, 0, 1, 0, 0,1,0,0,0),
outcome=c(0, 0, 0, 1, 0, 0, 1, 0, 0, 1,0,0,1,0),
time=c(100, 250, 220, 300, 240, 380, 150, 200, 320, 360,100,210,220,235),
sum=c(350, 350,520,520,620,620,150,520,520,360,310,310,455,455))
How can I write this in R ?