bind_rows_(x, .id) 中的错误:参数 1 必须有名称 [英] Error in bind_rows_(x, .id) : Argument 1 must have names

查看:18
本文介绍了bind_rows_(x, .id) 中的错误:参数 1 必须有名称的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是一个代码片段:

y <- purrr::map(1:2, ~ c(a=.x))
test1 <- dplyr::bind_rows(y)
test2 <- do.call(dplyr::bind_rows, y)

第一次调用 bind_rows (test1) 产生错误

The first call to bind_rows (test1) generates the error

Error in bind_rows_(x, .id) : Argument 1 must have names

另一方面,使用 do.call 来调用 bind_rows (test2),可以正常工作:

Using do.call to invoke bind_rows (test2), on the other hand, works as expected:

test2
# A tibble: 2 x 1
      a
  <int>
1     1
2     2

为什么?这是使用 dplyr 0.7.6 和 purrr 0.2.5.如果我使用 map_df 而不是 map,它会失败并出现相同的错误.

Why? This is using dplyr 0.7.6 and purrr 0.2.5. If I use map_df instead of map, it fails with the same error.

注意:在我看来,这个问题与 bind_rows_(x, .id) 中的错误:参数 1 必须在 purrr 中使用 map_df 的名称.

Note: It doesn't appear to me that this question is the same as Error in bind_rows_(x, .id) : Argument 1 must have names using map_df in purrr.

解决此问题的另一种方法是首先显式创建数据框:

The other way to address this issue is by explicitly creating a dataframe in the first place:

y <- purrr::map(1:2, ~ data.frame(a=.x))

test1test2 现在创建时没有错误并且完全相同.

test1 and test2 are now created with no errors and are identical.

或者,这一步创建 test2 数据框:

Alternatively,this creates the test2 data frame in one step:

purrr::map_df(1:2, ~ data.frame(a=.x))

推荐答案

来自 bind_rows 的文档:

请注意,由于历史原因,包含向量的列表总是作为数据帧处理.因此它们的向量被视为列而不是行,它们的内部名称被忽略

Note that for historical reasons, lists containg vectors are always treated as data frames. Thus their vectors are treated as columns rather than rows, and their inner names are ignored

这里,你的 y 构造只有内部名称——它是两个未命名的列表元素,每个元素包含一个长度为 1 的向量,向量元素名为 a.所以这个错误似乎在意料之中.

Here, your y as constructed has only inner names - it is two unnamed list elements, each containing a length-one vector with the vector element named a. So this error seems to be expected.

如果你命名列表元素,你可以看到它的行为与描述的一样,向量被视为列:

If you name the list elements, you can see that it behaves as described, with the vectors treated as columns:

library(tidyverse)
y <- map(1:2, ~ c(a=.x)) %>%
  set_names(c("a", "b"))
bind_rows(y)
#> # A tibble: 1 x 2
#>       a     b
#>   <int> <int>
#> 1     1     2

通过 do.call 提供 y 作为参数的不同之处在于它更像是编写 bind_rows(c(a = 1), c(a =2)).这不是包含向量的列表,而是单独的向量,因此它按预期按行绑定.

The difference with supplying y as arguments via do.call is that it's more like writing bind_rows(c(a = 1), c(a = 2)). This is not a list containing vectors, but separate vectors, so it binds by row as expected.

这篇关于bind_rows_(x, .id) 中的错误:参数 1 必须有名称的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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