In long-format datasets, level-2 (L2) variables may be partially missing within groups (e.g., subject ID). This function fills in missing L2 values using available information from other rows in the same group.

fill_missing_l2(data, id, vars)

Arguments

data

A data frame in long format.

id

Character string. Name of the grouping (L2) variable, e.g., "id".

vars

Character vector of variable names (L2 variables) whose missing values should be filled within groups.

Value

A data frame with filled-in L2 values. If conflicting non-missing values exist within a group, a message is printed and values are not imputed.

Examples

x <- data.frame(
  id = rep(1:5, each = 3),
  gender = c(1, 1, NA, 0, 0, 0, 1, NA, NA, NA, NA, NA, 1, 0, NA)
)
fill_missing_l2(x, "id", "gender")
#> Conflicting values in id 5 , cases  13, 14 
#> Complemented at id:  1 3 
#>    id gender
#> 1   1      1
#> 2   1      1
#> 3   1      1
#> 4   2      0
#> 5   2      0
#> 6   2      0
#> 7   3      1
#> 8   3      1
#> 9   3      1
#> 10  4     NA
#> 11  4     NA
#> 12  4     NA
#> 13  5      1
#> 14  5      0
#> 15  5     NA