我正在研究一个项目,我试图采取一个数据框架,只有一列,其中包含单词,然后试图建立一个循环,将从韦氏API拉一些数据的单词,然后将其放入一个新的数据框架。
最终的数据帧应该是这样的:
name | class | pronunciation | definition
ambit noun am*bit circuit, compass
我的代码:
words_for_loop
dataframe
diurnal
omnibus
chatelaine
mantic
limitrophe
oaf
代码:
for (i in seq_along(words_for_loop)) {
url_word_vector <- paste("https://www.dictionaryapi.com/api/v3/references/collegiate/json/", words_for_loop[[i]], "?key=numbers", sep = "")
data_holder <- tibble()
data_loop <- fromJSON(url_word_vector, flatten = TRUE) %>%
select(meta.id, fl, hwi.hw, shortdef) %>%
dplyr::rename(name = meta.id, class = fl, pronunciation = hwi.hw, definition = shortdef)
data_holder <-
data_holder %>%
bind_rows(data_loop)
}
结果是一个空标题。我想我是在正确的轨道上,因为运行url_word_vector
的结果是:
[1] "https://www.dictionaryapi.com/api/v3/references/collegiate/json/diurnal?key=99820690-b2a0-4aa3-902a-f54c7fa3c685"
[2] "https://www.dictionaryapi.com/api/v3/references/collegiate/json/omnibus?key=99820690-b2a0-4aa3-902a-f54c7fa3c685"
[3] "https://www.dictionaryapi.com/api/v3/references/collegiate/json/chatelaine?key=99820690-b2a0-4aa3-902a-f54c7fa3c685"
[4] "https://www.dictionaryapi.com/api/v3/references/collegiate/json/mantic?key=99820690-b2a0-4aa3-902a-f54c7fa3c685"
[5] "https://www.dictionaryapi.com/api/v3/references/collegiate/json/limitrophe?key=99820690-b2a0-4aa3-902a-f54c7fa3c685"
[6] "https://www.dictionaryapi.com/api/v3/references/collegiate/json/oaf?key=99820690-b2a0-4aa3-902a-f54c7fa3c685"
我只是不知道如何让它在那些单独的调用上循环。我需要在循环内嵌套一个循环吗?只是在寻找下一步。谢谢!
我认为最好将所有结果列在一个列表中,并在最后对它们进行rbind
。
library(dplyr)
library(jsonlite)
words_for_loop <- data.frame(V1 = c("diurnal", "omnibus", "chatelaine",
"mantic", "limitrophe", "oaf"))
home <- "https://www.dictionaryapi.com/api/v3/references/collegiate/json/"
key <- "my-api-key"
url_word_vector <- paste0(home, words_for_loop[[1]], "?key=", key)
do.call(rbind, lapply(url_word_vector, function(url) {
fromJSON(url, flatten = TRUE) %>%
select(meta.id, fl, hwi.hw, shortdef) %>%
rename(name = meta.id, class = fl, pronunciation = hwi.hw, definition = shortdef) %>%
as_tibble()
}))
#> # A tibble: 11 x 4
#> name class pronunciation definition
#> <chr> <chr> <chr> <list>
#> 1 diurnal:1 adjective di*ur*nal <chr [3]>
#> 2 diurnal:2 noun diurnal <chr [2]>
#> 3 omnibus:1 noun om*ni*bus <chr [2]>
#> 4 omnibus:2 adjective omnibus <chr [2]>
#> 5 justitia omnibus~ Latin phrase jus*ti*tia om*ni*bus <chr [1]>
#> 6 quod semper, quo~ Latin quotation from {i_~ quod sem*per, quod ub~ <chr [1]>
#> 7 the man on the C~ noun phrase the man on the Clapha~ <chr [1]>
#> 8 chatelaine noun chat*e*laine <chr [3]>
#> 9 mantic adjective man*tic <chr [1]>
#> 10 limitrophe adjective lim*i*trophe <chr [1]>
#> 11 oaf noun oaf <chr [2]>
由reprex包(v2.0.0)在2018-10-29上创建