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

查看:103
本文介绍了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))

test1 test2 现在已创建且没有错误并且相同。

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

在这里,您的<$ c构造的$ c> 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

与供应 y 的区别作为通过 do.call 的参数,它更像是编写 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天全站免登陆