我有一个data.frame
,带有两组ID,这两个ID可能都是多余的。
这是一个例子:
df <- data.frame(id1 = c("id.1","id.1","id.1","id.1","id.1","id.2","id.2","id.3"),
id2 = c("id.1.a","id.1.b","id.1.a","id.1.c","id.1.b","id.2.a","id.2.b","id.3.a"))
我想做的是添加另一个ID列,其中df$id1
将带有一个数字后缀,其值按df$id2
的顺序递增。
因此,对于上面的示例,所得的data.frame将为:
res.df <- data.frame(id1 = c("id.1","id.1","id.1","id.1","id.1","id.2","id.2","id.3"),
id2 = c("id.1.a","id.1.b","id.1.a","id.1.c","id.1.b","id.2.a","id.2.b","id.3.a"),
id3 = c("id.1.01","id.1.03","id.1.02","id.1.05","id.1.04","id.2.01","id.2.02","id.3"))
因此,由于id.1
两次映射到id.1.a
,两次映射到id.1.b
,一次映射到id.1.c
,因此它变成:id.1.01, id.1.03, id.1.02, id.1.05, id.1.04
有什么想法如何使用dplyr
或tidyr
做到这一点?
答案 0 :(得分:5)
id1
对行进行分组,因为这是我们要对行进行计数的分组。id1
,再按id2
row_number
附加到id1
的末尾。由于行按id1
和id2
排列,因此row_number
将保持该顺序示例:
df %>%
group_by(id1) %>%
arrange(id1, id2) %>%
mutate(id3 = paste0(id1, '.', row_number()))
# A tibble: 8 x 3
# Groups: id1 [3]
id1 id2 id3
<fct> <fct> <chr>
1 id.1 id.1.a id.1.1
2 id.1 id.1.a id.1.2
3 id.1 id.1.b id.1.3
4 id.1 id.1.b id.1.4
5 id.1 id.1.c id.1.5
6 id.2 id.2.a id.2.1
7 id.2 id.2.b id.2.2
8 id.3 id.3.a id.3.1
答案 1 :(得分:3)
我们可以在'id2'上直接使用row_number
library(dplyr)
df %>%
group_by(id1) %>%
mutate(id3 = paste0(id1, ".", row_number(id2)))
# A tibble: 8 x 3
# Groups: id1 [3]
# id1 id2 id3
# <fct> <fct> <chr>
#1 id.1 id.1.a id.1.1
#2 id.1 id.1.b id.1.3
#3 id.1 id.1.a id.1.2
#4 id.1 id.1.c id.1.5
#5 id.1 id.1.b id.1.4
#6 id.2 id.2.a id.2.1
#7 id.2 id.2.b id.2.2
#8 id.3 id.3.a id.3.1