【发布时间】:2020-12-25 09:57:20
【问题描述】:
我已将变量“县”列为一列,但当我尝试以这种方式使用 group_by_across 聚合它时:
testing4 <- testing2 %>%
group_by(across(-c(county, population))) %>%
summarise(pop=sum(population))
它给了我:
Error: Problem with `mutate()` input `..1`.
x Can't subset columns that don't exist.
x Column `county` doesn't exist.
Input `..1` is `across(-c(county, population))`.
i The error occurred in group 1: year = 1980, state = "AK", stfips = 2,
county = 2900.
Run `rlang::last_error()` to see where the error occurred.
但是,当我这样做时
testing3 <- testing2 %>%
group_by(year, state, stfips, race) %>%
summarise(pop = sum(population))
它运行良好。
编辑:有人要求 dput(head(testing2))
dput(head(testing2))
structure(list(year = c(1980L, 1980L, 1980L, 1980L, 1980L, 1980L
), state = c("AK", "AK", "AK", "AL", "AL", "AL"), stfips = c(2L,
2L, 2L, 1L, 1L, 1L), county = c(2900L, 2900L, 2900L, 1001L, 1001L,
1001L), race = c(1L, 2L, 3L, 1L, 2L, 3L), population = c(318054L,
13960L, 72666L, 24876L, 7193L, 148L)), row.names = c(NA, -6L), groups =
structure(list(
year = c(1980L, 1980L), state = c("AK", "AL"), stfips = 2:1,
county = c(2900L, 1001L), .rows = structure(list(1:3, 4:6), ptype =
integer(0), class = c("vctrs_list_of",
"vctrs_vctr", "list"))), row.names = 1:2, class = c("tbl_df",
"tbl", "data.frame"), .drop = TRUE), class = c("grouped_df",
"tbl_df", "tbl", "data.frame"))
【问题讨论】:
-
似乎
across()可能会导致问题。您没有在工作版本中使用它。如果您提供带有样本输入和所需输出的reproducible example,会更容易提供帮助。随意为您的示例使用内置数据集,而不是您自己的数据。 -
当我做
iris %>% group_by(across(-c(Sepal.Length, -Petal.Length)))时,它似乎有效。所以也许它真的是你特定的data.frame。分享dput(),前几行就可以了。dput(head(testing2)) -
我看到您正在使用的数据集已经分组。在做更多工作之前,您是否尝试过取消分组?
-
请参阅
https://github.com/tidyverse/dplyr/issues/5253- 如果数据已按其中一个变量分组,则使用across()和group_by()会失败。虽然错误消息不是特别有用。