I have a large dataset with thousands of measurements. What I want is to assign a visit number to each measurement so that all three consecutive measurements fall under the same visit number. After three consecutive measurements, the visit number increases. So the first three measurements are visit 1, the fourth to sixth measurements are visit 2, and so on. When there are only two or less measurements left, I want to mark the visit as missing.
Example dataset
DF <- data.frame(ID = rep("ID01", 10),
M = 1:10)
What I want:
DF$V <- c(rep(1:3, each = 3), NA)
Is there a way to this automatically?
Thanks for any help.
Update: What if each measurement contains numerous other measurements? So that:
DF <- data.frame(ID = rep("ID01", 50),
M0 = sample(50),
M = rep(1:10, each = 5))
What I want:
DF$V <- c(rep(rep(1:3, each = 3), each = 5), rep(NA, 5))
Even when the length of each level of DF$M changes (and thus is not fixed at n <- 15). E.g. length(DF$M == 1) = 21, length(DF$M == 2) = 26 etc.
Again, thanks for any help.