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

标签 r dplyr tidyr

我有一个数据集:

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 分组,并且

With grouped data frames, complete() operates within each group. Because of this, you cannot complete a grouping column.

?完成

所以要解决这个问题:

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

关于r - R中使用 "Complete()"函数时出错,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/73987696/

相关文章:

css - 增加 Shiny 应用程序中操作按钮的长度

r - 在 R : find all unique values in column separated by comma

r - tidyr::nest 在不同系统和包/R 版本上的不同行为

r - 如何按组回归线性模型并且仅改变斜率但保持截距相同?

r - 为什么 'object.size' 不接受 'units' 参数

r - purrr 找到最小值,然后用 case_when 标记

r - dplyr 在列子集上突变(所有这些列上的一个函数组合)

r - 使用 dplyr 和 do 进行多步预测

r - 在 dplyr 链中创建指标变量列

根据其他数据帧映射替换某些行中的值