本文介绍了Tidyverse方法按行绑定未命名向量的未命名列表-do.call(rbind,x)等效的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我经常发现一些问题,人们以某种​​方式以 unnamed 字符向量的 unnamed 列表结尾,他们想将它们按行绑定到 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"

一种典型的方法是使用 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

也许从R到 Reduce 效率较低。

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 方法将未命名字符向量的未命名列表按行绑定到 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)等效的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-25 11:58