Loop on the execution of variable

Hello! I want to know if it's possible to do something like this :

for (i in 1:6){
commun$diffdidi+1<-round(time_length(interval(commun$final.date_testDi,commun$final.date_testDi+1),"years"),2)
}

instead of that kind of code :

commun$diffd1d2<-round(time_length(interval(commun$final.date_testD1,commun$final.date_testD2),"years"),2)
commun$diffd2d3<-round(time_length(interval(commun$final.date_testD2,commun$final.date_testD3),"years"),2)
commun$diffd3d4<-round(time_length(interval(commun$final.date_testD3,commun$final.date_testD4),"years"),2)
commun$diffd4d5<-round(time_length(interval(commun$final.date_testD4,commun$final.date_testD5),"years"),2)
commun$diffd5d6<-round(time_length(interval(commun$final.date_testD5,commun$final.date_testD6),"years"),2)
commun$diffd6d7<-round(time_length(interval(commun$final.date_testD6,commun$final.date_testD7),"years"),2)

Indeed, in my code I have a lot of repition like this and it's not the most readable code.
Thank you for your time!

You can use the [[ operator to subset the data frame instead of $. That will allow you to construct strings of the column names and use those in the sub setting.

for ( i in 1:6){
  OutVar <- paste0("d", i, "d", i + 1)
  LeftVar <- paste0("final.date_testD", i)
  RightVar <- paste0("final.date_testD", i + 1)
  commun[[OutVar]] <- round(time_length(interval(commun[[LeftVar]], commun[[RightVar]]),"years"),2)
  #print(paste(OutVar, LeftVar, RightVar))
}

I included a print statement as a comment. If you remove the comment mark, you can see that the column names are correct, or not.

Edit:
The original code had one of the variable names wrong.

for ( i in 1:6){
  OutVar <- paste0("diffd", i, "d", i + 1)
  LeftVar <- paste0("final.date_testD", i)
  RightVar <- paste0("final.date_testD", i + 1)
  commun[[OutVar]] <- round(time_length(interval(commun[[LeftVar]], commun[[RightVar]]),"years"),2)
  #print(paste(OutVar, LeftVar, RightVar))
}

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.

If you have a query related to it or one of the replies, start a new topic and refer back with a link.