2014-02-09 46 views
3

我试图用相应组中的随机样本替换NA。例如,在第2行中,NA来自'法国',年龄和时间为'20 -30''30 -40'。因此,我想随机抽取所有其他“法国”,“20-30”,“30-40”观察值的“响应”列样本。使用'R'中的数据表替换NA反复使用

我有下面的代码很好用,但每个值被替换为相同的随机样本。例如,如果我有不止一个“法国”,“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)) 

回答

2

我会做这种方式:

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] 
2
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 

EDIT

第二步

在第一步中,您跨组(通过= ...)进行采样并获取R2的值。 第二步,使用没有NAs的Response值更新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 
+0

我不知道,但我认为随机抽样应只替换NA条目...例:R2的最后的值应该还是为0,只有NA可以是0/1。 – Arun

+0

这不可能是正确的,因为Arun指出第7行的最后一个值已经改变。 – user3154267

+0

好吧,这是一个跨群体的示例,也许你可以做到这一点,然后从R2中的响应更新非NA值。我编辑了答案。希望这可以帮助! – marbel