I have a data.table in R and want to create a new column. Let's say that I have the date column name saved as a variable and want to append _year
to that name in the new column. I'm able to do that the normal route by just specifying the name, but how can I create the new column name using the date_col
variable.
Here is what I've tried. The last two, which I want, don't work.
dat = data.table(one = 1:5, two = 1:5,
order_date = lubridate::ymd("2015-01-01","2015-02-01","2015-03-01",
"2015-04-01","2015-05-01"))
dat
date_col = "order_date"
dat[,`:=`(OrderDate_year = substr(get(date_col)[!is.na(get(date_col))],1,4))][]
dat[,`:=`(new = substr(noquote(get(date_col))[!is.na(noquote(get(date_col)))],1,4))][]
dat[,`:=`(paste0(date_col, "_year", sep="") = substr(noquote(get(date_col))[!is.na(noquote(get(date_col)))],1,4))][]
dat[,`:=`(noquote(paste0(date_col, "_year", sep="")) = substr(noquote(get(date_col))[!is.na(noquote(get(date_col)))],1,4))][]