这是一个代码片段:
y <- purrr::map(1:2, ~ c(a=.x))
test1 <- dplyr::bind_rows(y)
test2 <- do.call(dplyr::bind_rows, y)
第一次调用 bind_rows
(test1
) 会生成错误
Error in bind_rows_(x, .id) : Argument 1 must have names
另一方面,使用 do.call
调用 bind_rows
(test2
) 可以按预期工作:
test2
# A tibble: 2 x 1
a
<int>
1 1
2 2
为什么?这是使用 dplyr 0.7.6 和 purrr 0.2.5。如果我使用 map_df
而不是 map
,它会失败并出现相同的错误。
注意:在我看来,这个问题与 Error in bind_rows_(x, .id) : Argument 1 must have names using map_df in purrr 不同。 。
编辑:解决此问题的另一种方法是首先显式创建数据框:
y <- purrr::map(1:2, ~ data.frame(a=.x))
test1
和 test2
现在已创建,没有错误并且相同。
或者,这一步创建 test2
数据帧:
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
。所以这个错误似乎是预料之中的。
如果您命名列表元素,您可以看到它的行为如所描述的那样,其中向量被视为列:
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))
。这不是包含向量的列表,而是单独的向量,因此它按预期按行绑定(bind)。
关于r - Bind_rows_(x, .id) 中的错误 : Argument 1 must have names,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52505923/