自从新的 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))
Run Code Online (Sandbox Code Playgroud)
expect_output2应该有效地给出与expect_output.
现在...不推荐使用它们,我想不再使用它们,但我不确定如何做与上面相同的事情。
我基本上是在这里问这个问题,但这个问题现在在新dplyr版本中已经过时了。
当我使用上面的代码运行时,dplyr v1.0.0我收到警告消息:
Warning message:
The `...` argument of `group_keys()` is deprecated as of dplyr 1.0.0.
Please `group_by()` first
Run Code Online (Sandbox Code Playgroud)
所以我尝试执行以下操作
library(dplyr) # v1.0.0
rep_data %>%
group_by(x, y) %>%
mutate(expect_output3 = group_indices(.))
Run Code Online (Sandbox Code Playgroud)
这导致错误
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".
Run Code Online (Sandbox Code Playgroud)
保持group_indices的出来mutate工作正常,返回预期的载体,但是我想继续在管道链操纵我的数据,而不必为它分配就像我见过的其他问题,例如我不希望有这样做
rep_data$expect_output3 = rep_data %>% group_by(x,y) %>% group_indices()
Run Code Online (Sandbox Code Playgroud)
有没有办法group_indices()在维护我的管道链的同时将此向量添加到我的数据中?我很高兴使用不同的功能,group_indices()但我还没有找到适合我的目的的功能。
任何帮助,将不胜感激。谢谢!
该错误无法在 中重现dplyr 1.0.0,但group_indices已被弃用,请改用cur_group_id
library(dplyr)# 1.0.0
rep_data %>%
group_by(x, y) %>%
mutate(expect_output2 =cur_group_id())
# A tibble: 8 x 4
# Groups: x, y [7]
# x y expect_output expect_output2
# <chr> <chr> <dbl> <int>
#1 a v1 1 1
#2 a v1 1 1
#3 a v2 2 2
#4 a v3 3 3
#5 b v1 4 4
#6 b v2 5 5
#7 b v3 6 6
#8 c v3 7 7
Run Code Online (Sandbox Code Playgroud)