我正在尝试用来自适当组的随机样本替换NA。例如,在第 2 行中,NA 来自"法国",年龄和时间为"20-30"30-40"。因此,我想对所有其他"法国"、"20-30"、"30-40"观测值的"响应"列进行随机抽样。
我下面的代码效果很好,但每个值都替换为相同的随机样本。例如,如果我有多个"法国"、"20-30"、"30-40"NA,则它们对应的 R2 将是相同的。
我希望每个 NA 都独立采样,但 data.table 似乎"一次全部"完成,因此我不能这样做。有什么想法吗?
DT <- data.table(mydf, key = "Country,Age,Time")
DT[, R2 := ifelse(is.na(Response), sample(na.omit(Response), 1),
Response), by = key(DT)]
DT
# Index Country Age Time Response R2
# 1: 5 France 20-30 30-40 1 1
# 2: 6 France 20-30 30-40 NA 2
# 3: 7 France 20-30 30-40 2 2
# 4: 1 Germany 20-30 15-20 1 1
# 5: 2 Germany 20-30 15-20 NA 1
# 6: 3 Germany 20-30 15-20 1 1
# 7: 4 Germany 20-30 15-20 0 0
多年筹资金在哪里
mydf <- structure(list(Index = 1:7, Country = c("Germany", "Germany",
"Germany", "Germany", "France", "France", "France"), Age = c("20-30",
"20-30", "20-30", "20-30", "20-30", "20-30", "20-30"), Time = c("15-20",
"15-20", "15-20", "15-20", "30-40", "30-40", "30-40"), Response = c(1L,
NA, 1L, 0L, 1L, NA, 2L)), .Names = c("Index", "Country", "Age",
"Time", "Response"), class = "data.frame", row.names = c(NA, -7L))
我会这样做:
DT[, is_na := is.na(Response)]
nas <- DT[, sample(Response[!is_na], sum(is_na), TRUE) ,
by=list(Country, Age, Time)]$V1
DT[, R2 := Response][(is_na), R2 := nas]
set.seed(1234)
require(data.table)
DT <- data.table(mydf, key = "Country,Age,Time")
第一步
DT[, R2 := sample(na.omit(Response), length(Response), replace = T),
by = key(DT)]
DT
# Index Country Age Time Response R2
# 1: 5 France 20-30 30-40 1 1
# 2: 6 France 20-30 30-40 NA 2
# 3: 7 France 20-30 30-40 2 2
# 4: 1 Germany 20-30 15-20 1 1
# 5: 2 Germany 20-30 15-20 NA 0
# 6: 3 Germany 20-30 15-20 1 1
# 7: 4 Germany 20-30 15-20 0 1
编辑
第二步
第一步,跨组采样 (by = ...) 并获取 R2 的值。第二步,使用没有 NA 的响应值更新 R2。
DT[!is.na(Response), R2 := Response]
DT
# Index Country Age Time Response R2
# 1: 5 France 20-30 30-40 1 1
# 2: 6 France 20-30 30-40 NA 2
# 3: 7 France 20-30 30-40 2 2
# 4: 1 Germany 20-30 15-20 1 1
# 5: 2 Germany 20-30 15-20 NA 0
# 6: 3 Germany 20-30 15-20 1 1
# 7: 4 Germany 20-30 15-20 0 0