我有大约一年的R经验,但我真的很难绕过循环,我真的很感激你们有任何解释来回答!
我正在尝试使用Spotify API循环播放音乐类别列表( - 这是API术语,它们在Spotify应用程序中称为Genre / Mood)并检索播放列表列表。要检索一个类别的播放列表,我可以使用以下内容:
我认为这是一个相当简单的问题,不需要测试和获取密钥。 如果需要,可以使用Spotify文档(下面链接)轻松获取密钥,如果需要,我可以帮助设置(对于此或任何其他Spotify项目)。
#Setup up; Store keys and authenticate
ClientID <- "************"
ClientSecret <- "***********"
#OAuth
spotifyEndpoint <- oauth_endpoint(NULL,
"https://accounts.spotify.com/authorize",
"https://accounts.spotify.com/api/token")
spotifyApp <- oauth_app("spotify", ClientID, ClientSecret)
spotifyToken <- oauth2.0_token(spotifyEndpoint, spotifyApp)
#Create URL to call
CatPlaylist <- paste("https://api.spotify.com/v1/browse/categories/","funk","/playlists",sep="")
#Call api using GET
CatPlaylist <- httr::GET(CatPlaylist, spotifyToken)
#Transform results form JSON
CatPlaylist <- jsonlite::fromJSON(toJSON(content(CatPlaylist)))
#Transform into df
CatPlaylist <- t(data.frame(CatPlaylist$playlists$items$name))
我如何通过此循环收集其他类别,有效地用“派对”或“寒意”取代“funk”。
编辑:尝试添加到下方 我尝试了以下内容,其中
Cats
保留每次通话的完整网址。
final = NULL
for(i in 1:length(Cats)){
CatPlaylist <- paste("https://api.spotify.com/v1/browse/categories/",i,"/playlists",sep="")
CatPlaylist <- GET(CatPlaylist, spotifyToken)
CatPlaylist <- jsonlite::fromJSON(toJSON(content(CatPlaylist)))
CatPlaylist <- t(data.frame(CatPlaylist$playlists$items$name))
final <- rbind(CatPlaylist,final)}
API文档 https://developer.spotify.com/web-api/get-categorys-playlists/
系统信息:R 3.3.2 R Studio版本1.0.143 OS Sierra 10_12_3
提前致谢:)
答案 0 :(得分:0)
找到了解决方案。这种循环的斗争,所以任何建议都是受欢迎的,但与此同时解决方案是在其他人需要答案的情况下!
#Get category playlist - this works and returns a DF with rownames as categories. If country is not specified the API will return results which apply to all countries.
my.list <-list()
my.listOwner <-list()
for(i in 1:length(Categories$id)){
CatPlaylist <- paste0("https://api.spotify.com/v1/browse/categories/",Categories$id[i],"/playlists?limit=50&country=GB",sep="")
miss.id <- Categories$id[i]
list.name<- as.character(miss.id)
a <- GET(CatPlaylist, spotifyToken)
b <- jsonlite::fromJSON(toJSON(content(a)))
my.list[[list.name]] <-data.frame(unlist(b$playlists$items$name))
my.listOwner[[list.name]] <-data.frame(unlist(b$playlists$items$owner$id))
}
final <-do.call(rbind,my.list)
finalOwner <- do.call(rbind,my.listOwner)