dplyr 按组连接字符串 - 逐行
dplyr concatenate strings by group - row by row
我需要在 dplyr 中按组连接字符串,但生成的列应该只考虑前面的列,而不是前导列
我希望我的数据如下所示:
ID
message
messages_used
1
53
53
1
54
53,54
1
55
53,54,55
2
53
53
2
58
53,58
仅使用 dplyr
是否可以实现?
我们可以使用dplyr::group_by()
和purrr::accumulate()
:
dat <- data.frame(ID = c(1,1,1,2,2), message = c(53,54,55,53,58))
library(dplyr)
library(purrr)
dat %>%
group_by(ID) %>%
mutate(message_used = accumulate(message, ~ paste(.x, .y, sep =",")))
#> # A tibble: 5 x 3
#> # Groups: ID [2]
#> ID message message_used
#> <dbl> <dbl> <chr>
#> 1 1 53 53
#> 2 1 54 53,54
#> 3 1 55 53,54,55
#> 4 2 53 53
#> 5 2 58 53,58
由 reprex package (v2.0.1)
创建于 2022-05-11
您可以使用 Reduce(..., accumulate = TRUE)
来自 base
:
library(dplyr)
df %>%
group_by(ID) %>%
mutate(messages_used = Reduce(\(x, y) paste(x, y, sep = ", "), message, accumulate = TRUE)) %>%
ungroup()
# # A tibble: 5 x 3
# ID message messages_used
# <int> <int> <chr>
# 1 1 53 53
# 2 1 54 53, 54
# 3 1 55 53, 54, 55
# 4 2 53 53
# 5 2 58 53, 58
我需要在 dplyr 中按组连接字符串,但生成的列应该只考虑前面的列,而不是前导列
我希望我的数据如下所示:
ID | message | messages_used |
---|---|---|
1 | 53 | 53 |
1 | 54 | 53,54 |
1 | 55 | 53,54,55 |
2 | 53 | 53 |
2 | 58 | 53,58 |
仅使用 dplyr
是否可以实现?
我们可以使用dplyr::group_by()
和purrr::accumulate()
:
dat <- data.frame(ID = c(1,1,1,2,2), message = c(53,54,55,53,58))
library(dplyr)
library(purrr)
dat %>%
group_by(ID) %>%
mutate(message_used = accumulate(message, ~ paste(.x, .y, sep =",")))
#> # A tibble: 5 x 3
#> # Groups: ID [2]
#> ID message message_used
#> <dbl> <dbl> <chr>
#> 1 1 53 53
#> 2 1 54 53,54
#> 3 1 55 53,54,55
#> 4 2 53 53
#> 5 2 58 53,58
由 reprex package (v2.0.1)
创建于 2022-05-11您可以使用 Reduce(..., accumulate = TRUE)
来自 base
:
library(dplyr)
df %>%
group_by(ID) %>%
mutate(messages_used = Reduce(\(x, y) paste(x, y, sep = ", "), message, accumulate = TRUE)) %>%
ungroup()
# # A tibble: 5 x 3
# ID message messages_used
# <int> <int> <chr>
# 1 1 53 53
# 2 1 54 53, 54
# 3 1 55 53, 54, 55
# 4 2 53 53
# 5 2 58 53, 58