r - Bind_rows_(x, .id) 中的错误 : Argument 1 must have names

标签 r dplyr tidyverse

这是一个代码片段:

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))

test1test2 现在已创建,没有错误并且相同。

或者,这一步创建 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/

相关文章:

r - 变化线粗细图

sql - 数据库 tbl 上的 dplyr 函数是本地执行还是远程执行?

r - ggplot2:如何调整箱线图中的填充颜色(并更改图例文本)?

从数据框中删除每个唯一日期 var 小于 max(var) 的行

r - 使用 "[]"对 tibble 进行子集化会产生 "object not found"错误

删除数据框中单元格中包含多个字符串的行

r - 创建基于按 ID 分组的另一列的值重新启动的序列变量

r - 为 glm 使用 modelr::add_predictions

重新排序列 : split the second half of columns up so that they come as every second

r - 用于可视化或过滤 P 值的整洁 chisq.test 输出的函数