用连续的相应数值替换R数据框中的多个重复字符串
Substituting multiple repetitive strings in R dataframe with consecutive respective numeric values
我有一个包含 10000 行的数据框。
Author Value
aaa 111
aaa 112
bbb 156
bbb 165
ccc 543
ccc 256
每个作者有 4 行,所以我有 2500 个作者。
我想将所有字符串替换为数值。理想情况下 tidyverse
.
预期输出
Author Value
1 111
1 112
2 156
2 165
3 543
3 256
---------
2500 451
2500 234
谢谢!
使用match
和unique
:
match(dat$Author, unique(dat$Author))
# [1] 1 1 2 2 3 3
将其重新分配回原始列或新列,由您决定。
如果你想把它放在 dplyr 管道中,那么就
dat %>%
mutate(Author = match(Author, unique(Author)))
(正如 akrun 在他们的评论中发表的那样,我正在完成这个答案的同时 :-)。
数据
dat <- structure(list(Author = c("aaa", "aaa", "bbb", "bbb", "ccc", "ccc"), Value = c(111L, 112L, 156L, 165L, 543L, 256L)), class = "data.frame", row.names = c(NA, -6L))
我有一个包含 10000 行的数据框。
Author Value
aaa 111
aaa 112
bbb 156
bbb 165
ccc 543
ccc 256
每个作者有 4 行,所以我有 2500 个作者。
我想将所有字符串替换为数值。理想情况下 tidyverse
.
预期输出
Author Value
1 111
1 112
2 156
2 165
3 543
3 256
---------
2500 451
2500 234
谢谢!
使用match
和unique
:
match(dat$Author, unique(dat$Author))
# [1] 1 1 2 2 3 3
将其重新分配回原始列或新列,由您决定。
如果你想把它放在 dplyr 管道中,那么就
dat %>%
mutate(Author = match(Author, unique(Author)))
(正如 akrun 在他们的评论中发表的那样,我正在完成这个答案的同时 :-)。
数据
dat <- structure(list(Author = c("aaa", "aaa", "bbb", "bbb", "ccc", "ccc"), Value = c(111L, 112L, 156L, 165L, 543L, 256L)), class = "data.frame", row.names = c(NA, -6L))