自从新的 dplyr v1.0.0 更新发布以来,我注意到该功能group_indices()
有...
已弃用。我在工作中经常使用这个功能,并且我喜欢在mutate
.
例如使用dplyr v0.8.3
我能够非常轻松地做这样的事情:
#请注意,我没有运行此代码,因为我的计算机上不再有 v0.8.3。
library(dplyr) # v0.8.3
rep_data <- data.frame(
x = c("a", "a", "a", "a", "b", "b", "b", "c"),
y = c("v1", "v1", "v2", "v3", "v1", "v2", "v3", "v3"),
expect_output = c(1, 1, 2, 3, 4, 5, 6, 7)
)
rep_data %>%
mutate(expect_output2 = group_indices(x, y))
expect_output2
应该有效地给出相同的结果expect_output
.
现在既然...
已被弃用 我想不再使用它们,但我不确定如何做与上面相同的事情。
我基本上是在问这个问题HERE https://stackoverflow.com/questions/39650511/r-group-by-variable-and-then-assign-a-unique-id但这个问题现在已经过时了dplyr
版本。
当我使用上面的代码运行时dplyr v1.0.0
我收到警告消息:
Warning message:
The `...` argument of `group_keys()` is deprecated as of dplyr 1.0.0.
Please `group_by()` first
所以我尝试执行以下操作
library(dplyr) # v1.0.0
rep_data %>%
group_by(x, y) %>%
mutate(expect_output3 = group_indices(.))
这会导致错误
Error: Problem with `mutate()` input `expect_output3`.
x Input `expect_output3` can't be recycled to size 2.
i Input `expect_output3` is `group_indices(.)`.
i Input `expect_output3` must be size 2 or 1, not 8.
i The error occured in group 1: x = "a", y = "v1".
Keeping group_indices
出于mutate
工作正常并返回预期的向量,但是我想继续在管道链中操作我的数据,而不必像我在其他问题上看到的那样分配它
例如我不想这样做
rep_data$expect_output3 = rep_data %>% group_by(x,y) %>% group_indices()
有没有办法group_indices()
并在维护我的管道链的同时将此向量添加到我的数据中?我非常乐意使用与group_indices()
然而我还没有找到一个适合我的目的的。
任何帮助,将不胜感激。谢谢!