bind_rows_(x,.id)出错:参数1必须在purrr中使用map_df

Eva*_* O. 11 error-handling r dplyr purrr

我正在使用spotifyr包来抓取我的数据集中特定专辑的每首歌曲的音频功能.我的问题是我的数据集包含一些不在spotify上的艺术家 - 所以他们不应该返回任何值.

我的问题是,当我找到一个不在spotify上的艺术家时,我收到了这个错误:

Error in bind_rows_(x, .id) : Argument 1 must have names
Run Code Online (Sandbox Code Playgroud)

我已经尝试将函数包装在tryCatch中以获取NA有问题的行的每一列,但它似乎不起作用.

这是我的代码示例(仅供参考,您需要从spotify的网站获取API访问以运行spotifyr代码)

library(readr)
library(spotifyr)
library(dplyr)
library(purrr)

Sys.setenv(SPOTIFY_CLIENT_ID = "xxx") #xxx will be from spotify's website
Sys.setenv(SPOTIFY_CLIENT_SECRET = "xxx")
access_token <- get_spotify_access_token()

artist <- c("Eminem", "Chris Stapleton", "Brockhampton", "Big Sean, Metro Boomin")
album <- c("Revival", "From A Room: Volume 2", "SATURATION III", "Double or Nothing")
mydata <- data_frame(artist, album)

get_album_data <- function(x) {
  get_artist_audio_features(mydata$artist[x], return_closest_artist = TRUE) %>%
    filter(album_name == mydata$album[x])}

try_get_album_data <- function(x) {
  tryCatch(get_album_data(x), error = function(e) {NA})}

map_df(seq(1, 4), try_get_album_data)
Run Code Online (Sandbox Code Playgroud)

Pau*_*aul 11

问题是当它绑定行时,它无法绑定NA.要解决这个问题,只需使用data.frame()而不是NA.

这是一个更简单的问题示例.

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
Run Code Online (Sandbox Code Playgroud)

解决方案是替换NAdata.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
Run Code Online (Sandbox Code Playgroud)