我在R中有一個data.table,並且想要創建一個新列。假設我將日期列名稱保存爲變量,並且希望將_year附加到新列中的該名稱。我可以通過指定名稱來完成正常的路由,但是如何使用date_col變量創建新的列名稱。在data.table中動態創建新列
這是我試過的。最後兩個,我想要的,不工作。
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))][]