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

杀马特。学长 韩版系。学妹 提交于 2019-12-03 12:09:21

The problem is that when it binds the rows, it cannot bind with NA. To fix this just use data.frame() rather than NA.

Here's a simpler example of the problem.

library('dplyr')
library('purrr')

try_filter <- function(df) {
  tryCatch(
    df %>%
      filter(Sepal.Length == 4.6),
    error = function(e) NA)
}

map_df(
  list(iris, NA, iris),
  try_filter)
#> Error in bind_rows_(x, .id) : Argument 1 must have names

The solution is to replace NA with data.frame().

try_filter <- function(df) {
  tryCatch(
    df %>%
      filter(Sepal.Length == 4.6),
    error = function(e) data.frame())
}

map_df(
  list(iris, NA, iris),
  try_filter)
#>   Sepal.Length Sepal.Width Petal.Length Petal.Width Species
#> 1          4.6         3.1          1.5         0.2  setosa
#> 2          4.6         3.4          1.4         0.3  setosa
#> 3          4.6         3.6          1.0         0.2  setosa
#> 4          4.6         3.2          1.4         0.2  setosa
#> 5          4.6         3.1          1.5         0.2  setosa
#> 6          4.6         3.4          1.4         0.3  setosa
#> 7          4.6         3.6          1.0         0.2  setosa
#> 8          4.6         3.2          1.4         0.2  setosa
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!