r - 在 mutate 管道中按组获取唯一 ID

标签 r dplyr

自从新的 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但是这个问题现在已经过时了,新的 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".
饲养 group_indices出了mutate工作正常并返回预期的向量,但是我想继续在管道链中操作我的数据,而不必像我在其他问题上看到的那样分配它
例如我不想这样做
rep_data$expect_output3 = rep_data %>% group_by(x,y) %>% group_indices()
有没有办法到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

关于r - 在 mutate 管道中按组获取唯一 ID,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62562499/

相关文章:

r - “The format of predictions is incorrect”

r - 如何在 R 的正则表达式中仅提取捕获组

r - 包含唯一值数字的列

在 R 中使用 tidyverse 重新编码多个变量

r - 如果列表中存在值,则更改列的值

r - 使用 dplyr 创建具有多个分类/因子变量的汇总比例表

r - 更改 R 中 ggplot geom_polygon 的颜色方案

r - 包的安装具有非零退出状态 - Linux 服务器

r - 使用 dplyr 进行线性插值

使用 tidyverse 删除给定特定条件的重复条目