【发布时间】:2014-02-09 18:13:28
【问题描述】:
我正在尝试用来自适当组的随机样本替换 NA。例如,在第 2 行中,NA 来自“France”,年龄和时间为“20-30”“30-40”。因此,我想对所有其他 'France'、'20-30'、'30-40' 观察结果的 Response 列进行随机抽样。
下面的代码效果很好,但每个值都被相同的随机样本替换。例如,如果我有多个 'France'、'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 在哪里
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))
【问题讨论】:
标签: r data.table