我有一張這樣的桌子:
ID | 日期 | 地位 |
---|---|---|
101 | 2020-09-14 | 1 |
102 | 2020-09-14 | 1 |
103 | 2020-09-14 | 1 |
104 | 2020-09-14 | 2 |
105 | 2020-09-14 | 2 |
106 | 2020-09-14 | 2 |
但是想要這樣的表:
地位 | ID | 日期 |
---|---|---|
1 | 101,102,103 | 2020-09-14, 2020-09-14, 2020-09-14 |
1 | 104,105,106 | 2020-09-14, 2020-09-14, 2020-09-14 |
我目前正在使用的代碼:
注意:運行代碼之前的日期格式為 yyyy-mm-dd。
g1 <- df1 %>%
mutate(Date = as.Date(Date, format = '%Y%m%d')) %>%
group_by(status) %>%
summarise_at(c("ID", "Date"), list)
除了新表中的日期不在 yyyy-mm-dd 中之外,這似乎有效。例如,2021-06-10 正在轉換為 18788。
uj5u.com熱心網友回復:
一個可能的解決方案:
library(tidyverse)
df %>%
group_by(Status) %>%
summarise(ID = str_c(ID, collapse = ","), Date = str_c(Date, collapse = ","))
#> # A tibble: 2 × 3
#> Status ID Date
#> <int> <chr> <chr>
#> 1 1 101,102,103 2020-09-14,2020-09-14,2020-09-14
#> 2 2 104,105,106 2020-09-14,2020-09-14,2020-09-14
更簡潔的替代方案:
library(tidyverse)
df %>%
group_by(Status) %>%
summarise(across(c(ID, Date), str_c, collapse = ","))
#> # A tibble: 2 × 3
#> Status ID Date
#> <int> <chr> <chr>
#> 1 1 101,102,103 2020-09-14,2020-09-14,2020-09-14
#> 2 2 104,105,106 2020-09-14,2020-09-14,2020-09-14
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/491280.html