I have a dataframe, DATA, containing information on students and their test dates. I want to create a variable called WANT, where for all the STUDENTs you count the unique months (not the unique rows) as shown in the sample of the WANT variable below:
library(dplyr) set.seed(0) DATA <- data.frame("STUDENT" = sample(1:5, 100, r = T), "TESTDATE" = sample(seq(as.Date('2010/01/01'), as.Date('2010/12/31'), by="day"), 100, r=T)) DATA <- DATA %>% arrange(STUDENT, TESTDATE) DATA$WANT <- c(1,1,1,2,2,3,3,4,4,5,5,6,7,7,8,8,9,1,1,1,2,3,3,4,5,5,6,7,8,8,9,10,10, rep(NA, 67)) My attempt only does rows and it's not what I wish for
DATA %>% group_by(STUDENT) %>% mutate(WANT = 1:n())