【发布时间】:2021-10-16 01:49:17
【问题描述】:
我有一张这样的桌子:
| col1 | col2 | col3 |
|---|---|---|
| x | 1 | 4 |
| x | 2 | 5 |
| x | 3 | 6 |
| y | 1 | 4 |
| y | 2 | 5 |
| y | 3 | 6 |
我想根据它们在第一列中对应的内容将第二列和第三列中的元素组合为一个列表,如下所示:
| col1 | col2 | col3 |
|---|---|---|
| x | [1, 2, 3] | [4, 5, 6] |
| y | [1, 2, 3] | [4, 5, 6] |
我该怎么做呢?谢谢
【问题讨论】:
我有一张这样的桌子:
| col1 | col2 | col3 |
|---|---|---|
| x | 1 | 4 |
| x | 2 | 5 |
| x | 3 | 6 |
| y | 1 | 4 |
| y | 2 | 5 |
| y | 3 | 6 |
我想根据它们在第一列中对应的内容将第二列和第三列中的元素组合为一个列表,如下所示:
| col1 | col2 | col3 |
|---|---|---|
| x | [1, 2, 3] | [4, 5, 6] |
| y | [1, 2, 3] | [4, 5, 6] |
我该怎么做呢?谢谢
【问题讨论】:
这个使用 dplyr 的解决方案返回值的列表(不确定您是否想要字符串或列表,但您示例中的括号让我认为您想要列表...)
library(dplyr)
df1 %>%
group_by(col1) %>%
summarise(across(, list))
【讨论】:
这行得通吗:
library(dplyr)
library(stringr)
df %>% group_by(col1) %>% summarise(col2 = str_c('[',toString(col2),']'))
# A tibble: 2 x 2
col1 col2
<chr> <chr>
1 x [1, 2, 3]
2 y [1, 2, 3]
【讨论】:
您可以通过tidyr::pivot_wider 做到这一点
library(tidyr)
df %>%
pivot_wider(id_cols = col1,
values_from = -col1,
values_fn = list)
默认的values_fn 是list,所以从技术上讲,这里不需要它,但为了抑制警告消息,我明确表示了。
【讨论】:
使用来自base R的aggregate
aggregate(.~ col1, df1, list)
col1 col2 col3
1 x 1, 2, 3 4, 5, 6
2 y 1, 2, 3 4, 5, 6
df1 <- structure(list(col1 = c("x", "x", "x", "y", "y", "y"), col2 = c(1L,
2L, 3L, 1L, 2L, 3L), col3 = c(4L, 5L, 6L, 4L, 5L, 6L)),
class = "data.frame", row.names = c(NA,
-6L))
【讨论】: