更换NA和x27;在';R';

更换NA和x27;在';R';,r,data.table,R,Data.table,我试着用一个适当群体的随机样本来代替NA。例如,在第2行中,NA来自“法国”,年龄和时间为“20-30”“30-40”。因此,我想对所有其他“法国”、“20-30”、“30-40”观察结果的响应列进行随机抽样 我有下面的代码,它非常有效,但每个值都被相同的随机样本替换。例如,如果我有多个‘法国’、‘20-30’、‘30-40’NA,那么它们对应的R2都是相同的 我希望对每个NA进行独立采样,但data.table似乎“一次完成”了所有操作,因此我不能这样做。有什么想法吗 DT <- dat

我试着用一个适当群体的随机样本来代替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
DT
编辑

第二步

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
在第一步中,对accross组(by=…)进行采样并获得R2的值。 第二步,用没有NAs的响应值更新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
我会这样做:

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]
DT[,is_na:=is.na(响应)]

nas我不确定,但我认为随机抽样应该只替换NA条目。。。例如:R2的最后一个值仍然应该是0,只是NA可以是0/1。这并不正确,因为正如Arun指出的,第7行中的最后一个值已经更改。这是一个跨组的示例,也许您可以这样做,然后从R2中的响应更新非NA值。我已经编辑了答案。希望这有帮助@如果我是你,我会接受阿伦的回答。我相信他的答案更好。
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
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]