按行绑定未命名向量的未命名列表的 Tidyverse 方法 - do.call(rbind,x) 等效 [英] Tidyverse approach to binding unnamed list of unnamed vectors by row - do.call(rbind,x) equivalent

查看:14
本文介绍了按行绑定未命名向量的未命名列表的 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"

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

也许一种效率较低的方法是使用基于 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

然而,当我们考虑更现代的包,例如 dplyrdata.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.

因此,我的问题是什么是有效的 tidyversedata.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?

推荐答案

不完全确定效率,但使用 purrrtibble 的紧凑选项可能是:

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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆