用于循环读取现有数据框架的API响应

时间:2017-08-03 19:27:33

标签: json r api for-loop httr

我有一个数据框:

true

我的目标是使用Genius Lyric的API循环使用,以获取COL3中每个值的歌词网址。

如果我不循环播放这个并单独为每首歌做,那么我的输出就像这样:

df

                        NAME      ARTISTNAME                    COL3
1 Everything_Now (continued)     Arcade Fire Everything_Now%20(continued)%20Arcade%20Fire
2             Everything Now     Arcade Fire             Everything%20Now%20Arcade%20Fire
3              Signs of Life     Arcade Fire            Signs%20of%20Life%20Arcade%20Fire
4           Creature Comfort     Arcade Fire           Creature%20Comfort%20Arcade%20Fire
5                  Peter Pan     Arcade Fire                  Peter%20Pan%20Arcade%20Fire
6                  Chemistry     Arcade Fire                    Chemistry%20Arcade%20Fire

这是我到目前为止在for循环中的尝试,但是我收到了一个错误:

genius_url <- "https://api.genius.com/search?q=Everything_Now%20(continued)%20Arcade%20Fire"
getgeniuslyrics <- GET(genius_url, add_headers(Authorization = HeaderValue))
geniuslyrics <- jsonlite::fromJSON(toJSON(content(getgeniuslyrics)))
answer <- data.frame(geniuslyrics$response$hits$result$url[1])
answer

  X.https...genius.com.Arcade.fire.everything.now.continued.lyrics.
1    https://genius.com/Arcade-fire-everything-now-continued-lyrics 

str(answer)

'data.frame':   1 obs. of  1 variable:
$ X.https...genius.com.Arcade.fire.everything.now.continued.lyrics.: Factor w/ 1 level "https://genius.com/Arcade-fire-everything-now-continued-lyrics": 1

我收到的错误消息是:

for(i in 1:length(df[,3])) {
  genius_url <- paste("https://api.genius.com/search?q=", 
                      df3[i,3], 
                      sep="")
  getgeniuslyrics <- GET(genius_url, add_headers(Authorization = HeaderValue))
  geniuslyrics <- jsonlite::fromJSON(toJSON(content(getgeniuslyrics)))
  answer <- data.frame(geniuslyrics$response$hits$result$url[1])
  df[i,4] <- answer[1,]
}

希望这是有道理的。任何帮助都会很棒,谢谢。

1 个答案:

答案 0 :(得分:1)

您的数据框架是否已经有第三列,或者您是要从第1列和第2列创建它?我假设您必须在给定第一列和第二列的情况下创建第三列。

尝试使用格式化函数重写一个试用版:

 funfun <- function(...){
  x=unlist(list(...))
  A=paste(unlist(lapply(x,strsplit," ")),collapse = "%20")
  genius_url=paste0("https://api.genius.com/search?q=",A)
  getgeniuslyrics <- GET(genius_url, add_headers(Authorization = HeaderValue))
  geniuslyrics <- jsonlite::fromJSON(toJSON(content(getgeniuslyrics)))
  answer <- data.frame(geniuslyrics$response$hits$result$url[1])
  answer
  }

nom也许从这里你可以循环或使用应用函数:

  apply(df[,1:2],1,funfun)

如果您有第三列,那么您的生活会更轻松:

  funfun_1 <- function(x){
    genius_url=paste0("https://api.genius.com/search?q=",x)
    getgeniuslyrics <- GET(genius_url, add_headers(Authorization = HeaderValue))
    geniuslyrics <- jsonlite::fromJSON(toJSON(content(getgeniuslyrics)))
    answer <- data.frame(geniuslyrics$response$hits$result$url[1])
    answer
  }
sapply(df[,3],funfun_1)