Good morning everyone, I have a csv file (df2.csv) with several variables, as illustrated below (just for example):
CLASSE Variables Terms Number
1 DAT_1 20160701q 5
1 DAT_1 20160802q 2
1 DAT_1 20160901q 1
1 DAT_2 20161001q 1
1 DAT_2 20161201q 2
1 DAT_2 20170301q 3
2 DAT_1 20161001q 1
2 DAT_1 20161201q 2
2 DAT_1 20170301q 1
I want for each class (1 or 2 in this case), for each distinct date variable, if the number of individuals is less than 3, to group individuals with the next date. If I have a period of more than 3 individuals, in this case, I want to have a date like '20160701q-20160901q' instead of 20160701q and 20160901q separately. In this case, we group two dates or more to get a period of more than 3 individuals, and if the next date of the class has less than 3 individuals, we will group this date with the period before also. I started whit this code
for (n in df2$CLASSE){
for (k in df2$Variables){
for (i in 1:nrow(df2)){
if (df2$Number[i]<3){
rempl_date=paste(df2$Terms[i],df2$Terms[i+1], sep="-")
df2$Terms[i]<-rempl_date
next
}
}
}
}
But it doesn't work, I want to have this one after grouping:
CLASSE Variables Terms Number
1 DAT_1 20160701q 5
1 DAT_1 20160802q-20160901q 3
1 DAT_2 20161001q-20161201q 3
1 DAT_2 20170301q 3
2 DAT_1 20161001q-20170301q 4
I don't know what I must change else if you can help me, I hope I was clear. Thanks in advance