I am trying to replace NA's in a data set using a 'key'. The 'key' represents similarity based on some factors.
For example in the dataset below, the NA in row 5, can be replaced by 1, 0 or 1 on from rows 1, 2 and 6 respectively.
The code I have below works fine if aren't errors. For example the NA on row 3 errors because based on the key there are no similar rows. I would like to introduce something to say 'If error' (like in excel) replace that NA(not all the others) using a different key, which I will specify.
> s3ITR
Index Country Age Time Charity
1 1 France 30 40 1
2 2 France 30 40 0
3 3 France 30 50 NA
4 4 Germany 30 40 0
5 5 France 30 40 NA
6 6 France 30 40 1
7 7 Germany 30 40 1
8 8 Germany 30 40 1
DT <- data.table(s3ITR, key = "Country,Age,Time")
DT[, Impute := sample(na.omit(Charity), length(Charity), replace = T), by = key(DT)]
DT[!is.na(Charity), Impute := Charity]
DT[order(Index)]
S3<-mydf
S3$Charity <- DT$Impute
I'm new to 'R', any ideas ?