Last active
May 19, 2021 06:53
-
-
Save thedivtagguy/54c07163697610e929a88e3af0237d68 to your computer and use it in GitHub Desktop.
Genre Search
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# Code to search for an artist on Spotify and return their Spotify ID and genres. | |
# Requires the spotifyR package and for you to be authenticated with Spotify | |
# Read more here: https://github.com/charlie86/spotifyr | |
# And here: https://developer.spotify.com | |
# Extra: Could be adapted for all Spotify Features | |
library(tidyverse) | |
library(spotifyr) | |
# Authentication | |
Sys.setenv(SPOTIFY_CLIENT_ID = 'xxxxxxxxxxxxxxxxxxxxx') | |
Sys.setenv(SPOTIFY_CLIENT_SECRET = 'xxxxxxxxxxxxxxxxxxxxx') | |
access_token <- get_spotify_access_token() | |
# Function to Search Artist ID and Genres | |
get_artist_genre <- function(x) { | |
artist <- x | |
artist_info = NA | |
# error handling | |
tryCatch( | |
expr = { | |
artist_info <- spotifyr::search_spotify(artist, "artist") %>% | |
arrange(., -popularity) %>% | |
head(., 1) %>% | |
select(., genres, id) | |
message(paste("Search for", artist, "Successful")) | |
}, | |
error = function(e) { | |
message(paste("Searching error for", artist, "filling this row with NA")) | |
arist_info <- NA | |
}, | |
finally = { | |
return(artist_info) | |
} | |
) | |
} | |
# Select Only Artists | |
# songsdata is the original lyrics dataframe | |
artists <- unique(songsdata$artist) %>% | |
as_tibble() | |
# Run Our Function For Each Artist | |
artists <- artists %>% | |
mutate(num = 1:n()) %>% | |
tidyr::nest(data = c(value)) %>% | |
mutate(artist_features = purrr::map(data, ~ get_artist_genre(.$value)))%>% | |
unnest(., artist_features) %>% | |
unnest(., data) | |
# Clean Up | |
artists$num <- NULL | |
artists$artist_features <- NULL | |
artists$genres <- gsub('c\\("', "", artists$genres) | |
artists$genres <- gsub('"', "", artists$genres) | |
artists$genres <- gsub('\\)', "", artists$genres) | |
artists$genres <- gsub('character(0', "", artists$genres) | |
artists$genres <- gsub('character\\(0', "", artists$genres) | |
artists$genres <- gsub('list*', "", artists$genres) | |
artists$genres <- gsub('\\(', "", artists$genres) | |
# Now you can try joining the original lyric data set by the artist name |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment