在 R 中使用"Complete()"函数时出错



我有一个数据集:

structure(list(CC = c("Bagel Shop", "Bagel Shop", "Bagel Shop", 
"Bagel Shop", "Bagel Shop", "Bagel Shop", "Bagel Shop", "Bagel Shop", 
"Bagel Shop", "Bagel Shop"), `End Market` = c("Food Service", 
"Food Service", "Food Service", "Food Service", "Food Service", 
"Food Service", "Food Service", "Food Service", "Food Service", 
"Food Service"), Entity = c(6L, 6L, 6L, 6L, 6L, 6L, 6L, 6L, 6L, 
6L), SBPHYP = c(201901L, 201903L, 201904L, 201905L, 201907L, 
201908L, 201909L, 201910L, 201911L, 201912L), SBYEAR = c(2019L, 
2019L, 2019L, 2019L, 2019L, 2019L, 2019L, 2019L, 2019L, 2019L
), SBMONTH = c(1L, 3L, 4L, 5L, 7L, 8L, 9L, 10L, 11L, 12L), `Work Days` = c(21L, 
21L, 21L, 22L, 22L, 22L, 20L, 23L, 19L, 21L)), class = c("grouped_df", 
"tbl_df", "tbl", "data.frame"), row.names = c(NA, -10L), groups = structure(list(
CC = c("Bagel Shop", "Bagel Shop", "Bagel Shop", "Bagel Shop", 
"Bagel Shop", "Bagel Shop", "Bagel Shop", "Bagel Shop", "Bagel Shop", 
"Bagel Shop"), `End Market` = c("Food Service", "Food Service", 
"Food Service", "Food Service", "Food Service", "Food Service", 
"Food Service", "Food Service", "Food Service", "Food Service"
), SBMONTH = c(1L, 3L, 4L, 5L, 7L, 8L, 9L, 10L, 11L, 12L), 
.rows = structure(list(1L, 2L, 3L, 4L, 5L, 6L, 7L, 8L, 9L, 
10L), ptype = integer(0), class = c("vctrs_list_of", 
"vctrs_vctr", "list"))), class = c("tbl_df", "tbl", "data.frame"
), row.names = c(NA, -10L), .drop = TRUE))

我想扩展我的数据,每个名字都有12个月。我使用以下代码

library(dplyr)
library(tidyverse)
df <- df %>%
complete(CC, SBMONTH)

但是得到错误信息-

"Error in `dplyr::summarise()`:
! Problem while computing `..1 = complete(data = dplyr::cur_data(), ..., fill = fill, explicit = explicit)`.
*i The error occurred in group 1: CC = "Bagel Shop", End Market = "Food Service", SBMONTH = 1.
Caused by error:
! object 'CC' not found*

使用样品

df <- data.frame("Customer Code" = c("Bagel Shop", "Bagel Shop", "Bagel Shop", "Butcher", "Butcher", "Butcher", "Butcher", "Cafeteria"), "SBMONTH" = c(1:8))
df <- df %>%
complete(`Customer.Code`, SBMONTH)

一切正常。

怎么了?有其他方法吗?

您需要取消对数据帧的分组

您当前正在按CC和进行分组

对于分组的数据帧,complete((在每个组中操作。因此,您无法完成分组列。

?complete

所以要解决这个问题:

df |> 
ungroup() |>
complete(CC, SBMONTH)

最新更新