根据与另一个表的关系填充缺失值

Bha*_*gya 5 r data.table

我有两个数据表city_pop, 和city_subcity_pop是平均人口缺失一些值的城市列表。该city_sub表给出了两个可能的city_idsub_1sub_2),其avg_pop可以用于填充NAcity_popsub_1并按sub_2优先顺序使用。只需要替换中的NAavg_pop

如何在不使用 for 循环的情况下执行此操作?

city_id = c(1, 2, 3, 4, 5, 6)
avg_pop = c(100, NA, NA, 300, 400, NA)

city_pop = data.table(city_id, avg_pop)

   city_id avg_pop
1:       1     100
2:       2      NA
3:       3      NA
4:       4     300
5:       5     400
6:       6      NA

sub_1=c(2,1,4,3,1,3)
sub_2=c(5,5,6,6,2,4)

city_sub =data.table(city_id,sub_1,sub_2)

   city_id sub_1 sub_2
1:       1     2     5
2:       2     1     5
3:       3     4     6
4:       4     3     6
5:       5     1     2
6:       6     3     4
Run Code Online (Sandbox Code Playgroud)

预期输出 -

  city_id avg_pop
1       1     100
2       2     100
3       3     300
4       4     300
5       5     400
6       6     300
Run Code Online (Sandbox Code Playgroud)

Shr*_*ree 3

dplyr这是一种使用coalesce第一个非值的方法NA。我创建了一个单独的列,avg_pop2因为在这种情况下它看起来更安全,并且也可以轻松验证结果。

city_pop %>% 
  left_join(city_sub, by = "city_id") %>% 
  mutate(
    avg_pop2 = coalesce(
      avg_pop, avg_pop[match(sub_1, city_id)], avg_pop[match(sub_2, city_id)]
    )
  )

  city_id avg_pop sub_1 sub_2 avg_pop2
1       1     100     2     5      100
2       2      NA     1     5      100
3       3      NA     4     6      300
4       4     300     3     6      300
5       5     400     1     2      400
6       6      NA     3     4      300
Run Code Online (Sandbox Code Playgroud)