Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.9k views
in Technique[技术] by (71.8m points)

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

Here is a code snippet:

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

The first call to bind_rows (test1) generates the error

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

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

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.

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.

EDIT: 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 and test2 are now created with no errors and are identical.

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

purrr::map_df(1:2, ~ data.frame(a=.x))
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

From the documentation of 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

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

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

57.0k users

...