Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

I'm using the spotifyr package to scrape spotify audio features for every song of specific albums in my dataset. My issue is that my dataset consists of some artists that are not on spotify -- so they shouldn't be returning any values.

My issue is that when I get to an artist that is not on spotify, I get this error:

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

I've tried wrapping the function in tryCatch to get NA for each column of the problematic row, but it doesn't seem to work.

Here's an example of my code (FYI, you need to get API access from spotify's website to run the spotifyr code)

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)
like image 379
Evan O. Avatar asked Jan 30 '18 01:01

Evan O.


1 Answers

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
like image 70
Paul Avatar answered Nov 04 '22 17:11

Paul