0
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) ) 

After I use

data<-data%>%group_by(id,condition)%>%mutate(sumtime= sum(time))

I will change sumtime value to the value of condiotion==1 in each id 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(350, 350, 350, 350, 620, 620, 620, 520, 520, 520,310,310,310,310) )

How can I write in R ?

user224050
  • 317
  • 3
  • 10
  • Group by `id` and sum values only for which `condition == 1` returns `TRUE`, i.e. `time[condition == 1]` – markus Mar 02 '19 at 21:28
  • Possible duplicate of [How to sum a variable by group?](https://stackoverflow.com/questions/1660124/how-to-sum-a-variable-by-group) – markus Mar 02 '19 at 21:29
  • @markus I think you should undelete your answer. It seems to be what OP is looking for. We can still mark it as a duplicate if you want. – Gregor Thomas Mar 02 '19 at 21:40
  • @Gregor Thanks for your comment. I delete it because I thought it was a dupe and added the comment instead. Will give further assistance to OP if my comment is unclear. – markus Mar 03 '19 at 06:55

0 Answers0