Is there a simple way to create columns within a for loop? I know this question has been asked here multiple times and I have tried this solution adjusted to my case
for (i in 1:100) {
eval(parse(text = paste0('a$colum', i, ' <- whatever_you_want_your_column_to_contain')))
}
from one of the posts, but it did not help. I have an existing data table data and I am trying to create columns P_1 to P_30 within a for loop and then assign them NULL (I am just trying to pre-define the columns). I have tried this:
for (i in 1:30) {
eval(parse(text = paste0('data$P_', i, ' <- NULL')))
}
but without any success. Can you please suggest any approach that would work?
A related question - how to refer to those columns in another loop, if I have again column P_i where i is from 1 to 30, how to refer to data$P_i within a loop?
Edit:
I have this data table to make an example:
customer_id <- c("1","1","1","2","2","2","2","3","3","3")
account_id <- as.character(c(11,11,11,55,55,55,55,38,38,38))
obs_date <- c(as.Date("2017-01-01","%Y-%m-%d"), as.Date("2017-02-01","%Y-%m-%d"), as.Date("2017-03-01","%Y-%m-%d"),
as.Date("2017-12-01","%Y-%m-%d"), as.Date("2018-01-01","%Y-%m-%d"), as.Date("2018-02-01","%Y-%m-%d"),
as.Date("2018-03-01","%Y-%m-%d"), as.Date("2018-04-01","%Y-%m-%d"), as.Date("2018-05-01","%Y-%m-%d"),
as.Date("2018-06-01","%Y-%m-%d"))
variable <- c(87,90,100,120,130,150,12,13,15,14)
data <- data.table(customer_id,account_id,obs_date,variable)
and I found out that the problem is really in assigning that NULL to those columns, because when I am doing this based on the post's advice:
for (i in 1:30) {
eval(parse(text = paste0('data$P_', i, ' <- 1')))
}
it really works, just with the NULL instead of 1 it does not. So, it is not a bad advice, it just does not work with NULL.