r - Impute NA's with data.table from other values within a group -


consider following data table

library(data.table) dt <- data.table(sys_id = 1:9,              = c(11, 12, 12, 13, 14, 15, 15, 18, 18),              b = c(2, 1, 2, 1, 2, 1, 2, 1, 2),              age = c(13, na, 13, na, 11, na, 12, na, 12)) 

which gives following data table:

   sys_id  b age 1:      1 11 2  13 2:      2 12 1  na 3:      3 12 2  13 4:      4 13 1  na 5:      5 14 2  11 6:      6 15 1  na 7:      7 15 2  12 8:      8 18 1  na 9:      9 18 2  12 

the goal replace na's within groups of variable (1 or 2 rows per group) other value of age within same group. can done when group (of a) consists of 2 rows 1 na in 1 of 2 rows of group. value of age in row 4 can remain na. did following works:

dt[, age := unique(age[!is.na(age)]), = a] dt 

this last code gave me following data table:

   sys_id  b age 1:      1 11 2  13 2:      2 12 1  13 3:      3 12 2  13 4:      4 13 1  na 5:      5 14 2  11 6:      6 15 1  12 7:      7 15 2  12 8:      8 18 1  12 9:      9 18 2  12 

my problem:

although code works, code not intuitive (to me is). more understandable code shows each na in group of variable a, replacement must done age value nearest row (above or below within group). there (more intuitive) code data.table package?


Comments

Popular posts from this blog

python - Operations inside variables -

Generic Map Parameter java -

arrays - What causes a java.lang.ArrayIndexOutOfBoundsException and how do I prevent it? -