Replacing NA iteratively using data table in 'R'

I am trying to replace NA with a random sample from the corresponding group. For example, in line 2 of the National Assembly from "France" with an age and time of "20-30" 30-40. Therefore, I want to take a random sample of the column "Answer" for all other observations "France", "20-30", "30-40".

I have the code below that works fine, but each value is replaced with the same random sample. For example, if I had more than one β€œFrance”, β€œ20-30”, β€œ30-40”, then both of their respective R2 would be the same.

I would like each NA to be selected independently, but data.table seems to do it all at once, so I cannot do this. Any ideas?

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

where is 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))
+3
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

( =...) R2. , R2 Response, 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
+2

All Articles