【发布时间】:2019-06-17 17:26:51
【问题描述】:
数据
我有一个data.frame,看起来像这样:
df <- data.frame(id = c(1:10),
color = c(rep("red", 5), rep("blue", 5)))
df
#> id color
#> 1 1 red
#> 2 2 red
#> 3 3 red
#> 4 4 red
#> 5 5 red
#> 6 6 blue
#> 7 7 blue
#> 8 8 blue
#> 9 9 blue
#> 10 10 blue
预期结果
我正在尝试创建一个新列,例如 pair,它将一对 ID 分配给每组 2 个连续 ID。例如,我想以 data.frame 结尾,如下所示:
df
#> id color pair
#> 1 1 red 1
#> 2 2 red 1
#> 3 3 red 2
#> 4 4 red 2
#> 5 5 red 3
#> 6 6 blue 3
#> 7 7 blue 4
#> 8 8 blue 4
#> 9 9 blue 5
#> 10 10 blue 5
当前方法
我想知道的是,是否有比我已经在做的更简洁的方法来实现这一点。不过,我已经浏览了seq() 文档,但没有任何运气。这是我目前所拥有的,它给了我想要的输出,但不是很简洁。
df %>%
dplyr::mutate(pair = sort(rep(seq(length.out = nrow(df)/2),2)))
# id color pair
# 1 1 red 1
# 2 2 red 1
# 3 3 red 2
# 4 4 red 2
# 5 5 red 3
# 6 6 blue 3
# 7 7 blue 4
# 8 8 blue 4
# 9 9 blue 5
# 10 10 blue 5
除了seq()之外,有没有人有任何想法或其他功能可以完成这项工作?
【问题讨论】:
标签: r