0

I'm trying to write a function that can return the artist's genre on Spotify based on their Spotify ID. This is with the spotifyr package. Consider the following dataframe artists:

# A tibble: 6 x 2
  id                     name           
  <chr>                  <chr>          
1 6ltzsmQQbmdoHHbLZ4ZN25 Lord Huron     
2 35U9lQaRWSQISxQAB94Meo America        
3 22WZ7M8sxp5THdruNY3gXt The Doors      
4 2MSlGNpwXDScUdspOK6TS7 Home Free      
5 4GITZM5LCR2KcdlgEOrNLD The Foundations
6 2jgPkn6LuUazBoBk6vvjh5 The Zombies    

My function, get_genre is defined as follows:

get_genre <- function(x) {
    artist <- get_artist(x)
    artist <- enframe(artist)
    genre <- artist[3,2]
    genre <- as.data.frame(genre)
    return(genre)
}

For example, for the id 6ltzsmQQbmdoHHbLZ4ZN25 , it returns:

c("indie folk", "indie pop", "stomp and holler")

I would like to use it on each row of the artists dataframe, for each artist id. I tried doing this:

artists <- artists %>% mutate(genre = get_genre(id))

But this gives the following error:

Error: Problem with `mutate()` input `genre`. x length(url) == 1 is not TRUE i Input `genre` is `get_genre(id)`. 

How can I mutate a new column genre whose values are returned by my function for each artist id?

DPUT:

structure(list(id = c("6ltzsmQQbmdoHHbLZ4ZN25", "35U9lQaRWSQISxQAB94Meo", 
"22WZ7M8sxp5THdruNY3gXt", "2MSlGNpwXDScUdspOK6TS7", "4GITZM5LCR2KcdlgEOrNLD", 
"2jgPkn6LuUazBoBk6vvjh5"), name = c("Lord Huron", "America", 
"The Doors", "Home Free", "The Foundations", "The Zombies")), row.names = c(NA, 
-6L), class = c("tbl_df", "tbl", "data.frame"))

2 Answers 2

1

The function is not vectorized, use rowwise. Also since one id can return more than 1 genre you can use toString to combine everything in one comma separated string.

library(dplyr)

artists <- artists %>% rowwise() %>% mutate(genre = toString(get_genre(id)))
Sign up to request clarification or add additional context in comments.

2 Comments

Thank you! I need to read up rowwise and vectorized functions, I think I'm still unclear on the distinction.
Vectorized functions are faster than rowwise, because the first one apply a function in every element of a vector or column "at the same time". rowwise apply the function at one row at a time. Btw, @Ronak Shah, please, can you provide a vectorized version of this?
0

We can use map

library(purrr)
library(dplyr)
artists <- artists %>%
              mutate(genre = map_chr(id, ~ toString(get_genre(.x))))

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.