In STATA creating a variable dynamically within a loop is easy because the quotations `' identify the iterator. This example is to create a binary variable Y200X that takes value 1 if the Year is lesser than year 200X:
set obs 10
gen Year = 2005
replace Year = 2010 if _n > 4
forvalues y = 2005(1)2020 {
gen byte Y`y' = 0
replace Y`y' = 1 if Year < `y'
}
In R the iterator cannot be used directly for creating the variable name. The best I found was first create variables in the loop then assemble them back into the dataframe outside the loop:
Year <- c(2005,2010,1996,1994,2001,2006,2019,2021, 2018,1987)
ls.output <- as.data.frame(Year)
for(y in 2005:2020) {
assign(paste0("Y",y), ifelse(ls.output$Year < y, 1, 0))
}
ls.output<- cbind(ls.output, Y2005,Y2006,Y2007,Y2009, Y2010)
Is there a better way to do this directly in the loop?