0

I have a dataframe from a survey in which users were asked questions across multiple days. I need to create a column which contains an integer equal to what number survey it is for each user. Something like this:

User Survey_Number
1    1
1    2
1    3
1    4
2    1
2    2
3    1
3    2
3    3
4    1
4    2
5    1

How do I increment through each row for each user to assign the value for Survey_Number? This is what I have, though I know it's probably not on the right track. It sets Survery_Number equal to 0 in each row. (Yes, I know I'm bad at this)

for(i in(data.dat$User))
  k<-0
  for(j in (data.dat$Survey_Number))
    data.dat$Survery_Number<-k
    k<-(k+1)
  • It'd be easier for you to find help if you showed us what `data.dat` looks like. Can you share it by pasting the output of `dput(head(data.dat))` in your question? If not, can you create a dummy dataset? See [here](https://stackoverflow.com/questions/5963269/how-to-make-a-great-r-reproducible-example) for more info. – Andrea M Apr 10 '22 at 21:39
  • 1
    (1) You could use `dplyr`: `data.dat %>% group_by(User) %>% mutate(Survey_Number = row_number())`. – Martin Gal Apr 10 '22 at 21:41
  • 1
    In base: `data.dat$Survey_Number <- unlist(tapply(data.dat$User, data.dat$User, seq_along))` – Axeman Apr 10 '22 at 21:54

0 Answers0