我有類似這樣的資料:
library(data.table)
library(stringr)
dt <- data.table(id=1:20,
month_1=rep(sample(1:12, 20, replace = T)),
month_2=rep(sample(1:12, 20, replace = T)),
month_3=rep(sample(1:12, 20, replace = T)),
month_4=rep(sample(1:12, 20, replace = T)),
year_1=rep(sample(2010:2020, 20, replace = T)),
year_2=rep(sample(2010:2020, 20, replace = T)),
year_3=rep(sample(2010:2020, 20, replace = T)),
year_4=rep(sample(2010:2020, 20, replace = T)))
我正在嘗試執行這 4 個命令
dt[,date_1:= as.Date(paste0(year_1, "-", str_pad(month_1, 2, pad = "0"), "-", 01))]
dt[,date_2:= as.Date(paste0(year_2, "-", str_pad(month_1, 2, pad = "0"), "-", 01))]
dt[,date_3:= as.Date(paste0(year_3, "-", str_pad(month_1, 2, pad = "0"), "-", 01))]
dt[,date_4:= as.Date(paste0(year_4, "-", str_pad(month_1, 2, pad = "0"), "-", 01))]
如何使用 for 回圈來做到這一點?
我努力了:
for (i in 1:4){
dt[,date_i:= as.Date(paste0(year_i, "-", str_pad(month_i, 2, pad = "0"), "-", 01))]
}
但得到錯誤:
paste0(year_i, "-", str_pad(month_i, 2, pad = "0"), "-", 1) 出錯:找不到物件 'year_i'
uj5u.com熱心網友回復:
在不進行重大更改的情況下修復損壞的回圈:
for (i in 1:4) {
date_var = paste0("date_", i)
year_var = paste0("year_", i)
month_var = paste0("month_", i)
dt[, (date_var) := as.Date(paste0(get(year_var), "-", str_pad(get(month_var), 2, pad = "0"), "-", 01))]
}
重構一下并洗掉 stringr 依賴項:
for (i in 1:4) {
year_var = paste0("year_", i)
month_var = paste0("month_", i)
set(
x = dt,
j = paste0("date_", i),
value = as.Date(paste(dt[[year_var]], dt[[month_var]], "1"), "%Y %m %d")
)
}
uj5u.com熱心網友回復:
或與lapply:
i <- 1:4
dt[,paste0("date_i",i):=lapply(i,function(i) as.Date(paste0(get(paste0("year_",i)), "-", str_pad(month_1, 2, pad = "0"), "-", 01)))][]
uj5u.com熱心網友回復:
解決問題的一種方法:
i = 1:4
dt[, paste0("date_", i) := Map(\(x,y) as.Date(sprintf("%d-d-01", x, y)),
mget(paste0("year_", i)),
mget(paste0("month_", i)))]
轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/528591.html
標籤:r循环for循环数据表
