我正在嘗試在串列串列中回圈并將結果系結到單個資料框中。我的代碼的第一部分完美運行。但是,當我嘗試從結果串列 (prueba) 回圈并制作一個資料框時,我沒有所需的輸出。
第一部分(可重現的示例):
library(jsonlite)
library(httr)
lista <- c("BNBBTC","ETHBTC")
prueba <- list()
for (i in lista) {
prueba[[i]] <- GET(paste0("https://api1.binance.com/api/v3/ticker/24hr?symbol=",i))
}
至于第二部分,我知道我想要的是 aux_final 資料框。但是,我不知道如何在不使用 $ 符號的情況下進行回圈。
aux <- fromJSON(rawToChar(prueba$ETHBTC$content))
aux <- data.frame(aux)
aux_2 <- fromJSON(rawToChar(prueba$BNBBTC$content))
aux_2 <- data.frame(aux_2)
aux_final <- bind_rows(aux,aux_2)
在這種情況下,我想回圈代幣“ETHBTC”或“BNBBTC”的名稱,并獲得像 aux_final 這樣的結果資料幀。
uj5u.com熱心網友回復:
你可以用類似的方式回圈
library(dplyr)
aux_final <- data.frame()
for (i in prueba){
aux <- i[["content"]] %>% rawToChar %>% fromJSON %>% data.frame
aux_final <- bind_rows(aux_final, aux)
}
aux_final
symbol priceChange priceChangePercent weightedAvgPrice prevClosePrice lastPrice lastQty bidPrice bidQty askPrice
1 ETHBTC 0.00062600 0.892 0.07026676 0.07014400 0.07077000 0.00990000 0.07077400 2.57850000 0.07077500
2 BNBBTC 0.00038000 4.428 0.00873508 0.00858200 0.00896200 0.53600000 0.00896100 44.73800000 0.00896200
askQty openPrice highPrice lowPrice volume quoteVolume openTime closeTime firstId lastId count
1 1.00280000 0.07014400 0.07140000 0.06913300 76608.18500000 5383.00905379 1.635728e 12 1.635815e 12 306316825 306518132 201308
2 3.68300000 0.00858200 0.00905300 0.00843900 212858.68100000 1859.33793552 1.635728e 12 1.635815e 12 165844663 166011284 166622
uj5u.com熱心網友回復:
使用lapplyand 的一種方式glue:
library(jsonlite)
library(httr)
library(glue)
library(magrittr)
lista <- c("BNBBTC","ETHBTC")
aux_final <- lapply(lista, function(x){
'https://api1.binance.com/api/v3/ticker/24hr?symbol={x}' %>% glue %>% GET %>% {.$content} %>%
rawToChar %>% fromJSON %>% data.frame
}) %>% do.call(rbind,.)
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/344519.html
