Tidyverse 按行绑定未命名向量列表的方法 - do.call(rbind,x) 等效 [英] Tidyverse approach to binding unnamed list of unnamed vectors by row - do.call(rbind,x) equivalent
问题描述
我经常发现人们以某种方式以未命名 未命名字符向量列表结束的问题,他们希望将它们逐行绑定到 data.frame
.这是一个例子:
I often find questions where people have somehow ended up with an unnamed list of unnamed character vectors and they want to bind them row-wise into a data.frame
. Here is an example:
library(magrittr)
data <- cbind(LETTERS[1:3],1:3,4:6,7:9,c(12,15,18)) %>%
split(1:3) %>% unname
data
#[[1]]
#[1] "A" "1" "4" "7" "12"
#
#[[2]]
#[1] "B" "2" "5" "8" "15"
#
#[[3]]
#[1] "C" "3" "6" "9" "18"
一种典型的方法是使用来自基础 R 的 do.call
.
One typical approach is with do.call
from base R.
do.call(rbind, data) %>% as.data.frame
# V1 V2 V3 V4 V5
#1 A 1 4 7 12
#2 B 2 5 8 15
#3 C 3 6 9 18
也许一种效率较低的方法是使用 base R 中的 Reduce
.
Perhaps a less efficient approach is with Reduce
from base R.
Reduce(rbind,data, init = NULL) %>% as.data.frame
# V1 V2 V3 V4 V5
#1 A 1 4 7 12
#2 B 2 5 8 15
#3 C 3 6 9 18
但是,当我们考虑诸如 dplyr
或 data.table
等更现代的包时,可能会立即想到的一些方法不起作用,因为向量未命名或不是列表.
However, when we consider more modern packages such as dplyr
or data.table
, some of the approaches that might immediately come to mind don't work because the vectors are unnamed or aren't a list.
library(dplyr)
bind_rows(data)
#Error: Argument 1 must have names
library(data.table)
rbindlist(data)
#Error in rbindlist(data) :
# Item 1 of input is not a data.frame, data.table or list
一种方法可能是在向量上set_names
.
One approach might be to set_names
on the vectors.
library(purrr)
map_df(data, ~set_names(.x, seq_along(.x)))
# A tibble: 3 x 5
# `1` `2` `3` `4` `5`
# <chr> <chr> <chr> <chr> <chr>
#1 A 1 4 7 12
#2 B 2 5 8 15
#3 C 3 6 9 18
但是,这似乎比需要的步骤更多.
However, this seems like more steps than it needs to be.
因此,我的问题是什么是有效的 tidyverse
或 data.table
方法来绑定 unnamed 列表 unnamed 字符向量到 data.frame
行吗?
Therefore, my question is what is an efficient tidyverse
or data.table
approach to binding an unnamed list of unnamed character vectors into a data.frame
row-wise?
推荐答案
不完全确定效率,但使用 purrr
和 tibble
的紧凑选项可能是:
Not entirely sure about efficiency, but a compact option using purrr
and tibble
could be:
map_dfc(purrr::transpose(data), ~ unlist(tibble(.)))
V1 V2 V3 V4 V5
<chr> <chr> <chr> <chr> <chr>
1 A 1 4 7 12
2 B 2 5 8 15
3 C 3 6 9 18
这篇关于Tidyverse 按行绑定未命名向量列表的方法 - do.call(rbind,x) 等效的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!