如何在缺少值的地方插入0

时间:2019-12-22 18:24:19

标签: r dataframe

我有一个名为dets_per_month的数据框,看起来像这样...

**Zone     month   yearcollected   total**
1         Jul        2017            183
1         Jul        2015            18
1         Aug        2015            202
1         Aug        2017            202
1         Aug        2017            150
1         Sep        2017            68
2         Apr        2018            65
2         Jun        2018            25
2         Sep        2018            278

我试图输入0的月份在特定区域中没有总数。这是我尝试输入0的代码

complete(dets_per_month, nesting(zone, month), yearcollected = 2016:2018, fill = list(count = 0))

但是此输出不会给我任何0,而是将其添加到原始数据帧的列中。 谁能告诉我如何为此获得0?

1 个答案:

答案 0 :(得分:0)

completeZone分组后,可以使用yearcollected。我们可以使用month.abb,它是英语月份名称的内置常量。

library(dplyr)

df %>%
  group_by(Zone, yearcollected) %>%
  tidyr::complete(month = month.abb, fill = list(total = 0))

#    Zone yearcollected month total
#   <int>         <int> <chr> <dbl>
# 1     1          2015 Apr       0
# 2     1          2015 Aug     202
# 3     1          2015 Dec       0
# 4     1          2015 Feb       0
# 5     1          2015 Jan       0
# 6     1          2015 Jul      18
# 7     1          2015 Jun       0
# 8     1          2015 Mar       0
# 9     1          2015 May       0
#10     1          2015 Nov       0
# … with 27 more rows

数据

df <- structure(list(Zone = c(1L, 1L, 1L, 1L, 1L, 1L, 2L, 2L, 2L), 
month = structure(c(3L, 3L, 2L, 2L, 2L, 5L, 1L, 4L, 5L), .Label = c("Apr", 
"Aug", "Jul", "Jun", "Sep"), class = "factor"), yearcollected = c(2017L, 
2015L, 2015L, 2017L, 2017L, 2017L, 2018L, 2018L, 2018L), 
total = c(183L, 18L, 202L, 202L, 150L, 68L, 65L, 25L, 278L
)), class = "data.frame", row.names = c(NA, -9L))