问题描述
是否可以将包含具有 3 个元素的向量的列拆分为数据框内的 3 个单独的列?
Is it possible to split a column containing vectors with 3 elements into 3 seperate columns inside of a dataframe??
一列包含像 c("aa","bb","cc")
这样的向量应该变成 3 列包含像
One column containing vectors like c("aa","bb","cc")
should turn into 3 columns containing singular values like
"aa" "bb" "cc"
声称执行此操作的每个 tidyr 或 dyplr 操作仅适用于字符串并将我的列的内容格式化为字符串 "c("aa","bb","cc")"
(?!) 在分裂之前.
Every tidyr or dyplr operation that claims to do this only works on strings and formats the contents of my colum as the String "c("aa","bb","cc")"
(?!) before splitting.
有没有可以将向量分成单独列的库?
Is there any library that can split vectors into seperate columns?
推荐答案
这是一个使用 dplyr
和 tidyr
的解决方案:
Here's one solution using dplyr
and tidyr
:
library(dplyr)
library(tidyr)
df %>%
unnest(a) %>%
group_by(id) %>%
mutate(key = row_number()) %>%
spread(key, a)
# A tibble: 2 x 4
# Groups: id [2]
id `1` `2` `3`
* <dbl> <chr> <chr> <chr>
1 1.00 aa bb cc
2 2.00 aa bb cc
使用由弗洛里安提供的数据:
Using data, provided by Florian:
df <- data.frame(
id = c(1,2),
a = I(list(c("aa", "bb", "cc"), c("aa", "bb", "cc")))
)
这篇关于R 将包含向量的列拆分为多列的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!