根据值条件在数据框中插入丢失的行

时间:2019-11-15 16:11:59

标签: r dplyr tidyr

给出这样的数据框

country      rest         count
Argentina    pizza        26
Argentina    asador       22
Brazil       feijoada     52
Brazil       pizza        67
Germany      pizza        22
Germany      biergarten   52
Germany      kebab        20

让我们假设,“剩余”列中的所有唯一值都应与数据框中的国家/地区一样多的行来表示,即使它们没有值也是如此。我想要的输出看起来像这样:

country      rest         count
Argentina    pizza        26
Argentina    asador       22
Argentina    feijoada     0
Argentina    biergarten   0
Argentina    kebab        0
Brazil       pizza        67
Brazil       feijoada     52
Brazil       asador       0
Brazil       biergarten   0
Brazil       kebab        0
Germany      pizza        22
Germany      biergarten   52
Germany      kebab        20
Germany      asador       0
Germany      feijoada     0

是否有通过dplyr达到此输出的简单方法?

1 个答案:

答案 0 :(得分:2)

tidyr::complete(dat, country, rest, fill=list(count=0))
# # A tibble: 15 x 3
#    country   rest       count
#    <chr>     <chr>      <dbl>
#  1 Argentina asador        22
#  2 Argentina biergarten     0
#  3 Argentina feijoada       0
#  4 Argentina kebab          0
#  5 Argentina pizza         26
#  6 Brazil    asador         0
#  7 Brazil    biergarten     0
#  8 Brazil    feijoada      52
#  9 Brazil    kebab          0
# 10 Brazil    pizza         67
# 11 Germany   asador         0
# 12 Germany   biergarten    52
# 13 Germany   feijoada       0
# 14 Germany   kebab         20
# 15 Germany   pizza         22