【问题标题】:Use bind_rows to convert list of vectors to dataframe [duplicate]使用 bind_rows 将向量列表转换为数据框 [重复]
【发布时间】:2020-11-02 12:29:41
【问题描述】:

我有一个要转换为数据框的向量列表。

代码

a <- list( c(1,2,3,4), 
           c(1,2,3,4), 
           c(4,5,6,3), 
           c(6,3,2,6))

this post 的帮助下,我能够通过以下方式做到这一点:

library(tidyverse)
a %>% 
   reduce(rbind) %>% 
   as.data.frame()

> a %>% reduce(rbind) %>% as.data.frame()
      V1 V2 V3 V4
out    1  2  3  4
elt    1  2  3  4
elt.1  4  5  6  3
elt.2  6  3  2  6

我想使用purrrbind_rows()函数(a %&gt;% bind_rows),因为它看起来更方便。但是,这会产生错误:

错误:参数 1 必须有名称。

问题

  1. 这里发生了什么?
  2. 我怎样才能防止它发生;)?

【问题讨论】:

  • 可能基数:do.call(rbind, a)
  • bind_rows() 最初是一个dplyr 函数,旨在将data.frames 或tibbles 绑定在一起。由于data.frame 列有名称,bind_rows 期望输入被命名,这就是你得到错误的原因。 rbind 在这里不那么严格。

标签: r dplyr purrr


【解决方案1】:

一个选项可能是:

map_dfr(a, ~ set_names(.x, paste0("V", seq_along(.x))))

     V1    V2    V3    V4
  <dbl> <dbl> <dbl> <dbl>
1     1     2     3     4
2     1     2     3     4
3     4     5     6     3
4     6     3     2     6

【讨论】:

  • 遇到同样的错误? (可能版本问题:R 版本 3.6.2;tidyverse_1.3.0)
  • @zx8754 是的,bind_rows(a) 我得到与 OP 相同的错误。
  • 没有必要使用purrrmap():a %&gt;% set_names(., c("V1", "V2", "V3", "V4")) %&gt;% bind_rows
  • @TimTeaFan set_names() 实际上来自purrr :) 此外,您的解决方案是根据需要以相反的方式绑定。
  • @tmfmnk 效果很好!只是为了我的理解:~ 实际上是做什么的?
猜你喜欢
  • 2021-06-25
  • 2017-09-25
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-04-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多