all:
The problem came when I tried to use for loop to create 5 dataframes and assign these five dataframes to a list. Please see an example:
library(data.table)
set.seed(123)
df <- as.data.table(list(rnorm(10,1,1), rnorm(10,1,1)))
list <- list()
for(i in 2011:2015){
list[[paste0("A_",i)]] <- df[, year := as.numeric(i)]
}
So, as I expected, the value of year variable should be as same as i in each element. For example, value of year in list[1] should be 2011. However, the above code returns 2015 for year in all elements:
> list[1]
$A_2011
V1 V2 year
1: 0.4395244 2.2240818 2015
2: 0.7698225 1.3598138 2015
3: 2.5587083 1.4007715 2015
4: 1.0705084 1.1106827 2015
5: 1.1292877 0.4441589 2015
6: 2.7150650 2.7869131 2015
7: 1.4609162 1.4978505 2015
8: -0.2650612 -0.9666172 2015
9: 0.3131471 1.7013559 2015
10: 0.5543380 0.5272086 2015
I can't figure out what's wrong with my code. I would appreciate if anyone could point out the problem here. I would like to see any other solutions using lapply or so, if any. Many thanks!
list[[paste0("A_",i)]]$year <- iin your loop.yrs = 2011:2015; res <- df[rep(1:.N, length(yrs))][, year := rep(yrs, each = nrow(df))][]ordf[, rbindlist(Map(cbind, .(.SD), year = yrs))]