I'm trying to loop inside a list of lists and to bind the results into a single data frame. The first part of my code works perfectly. However, when I try to loop from the resulting list (prueba) and to make one single data frame I do not have the desired output.
First part (reproducible example):
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))
}
As for the second part, I know what I want is the aux_final data frame. However, I don't know how to loop without using the $ symbol.
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)
I want to loop the name of the coin "ETHBTC" or "BNBBTC" in this case and to have a resulting data frame like aux_final.
CodePudding user response:
You can loop in similar way
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
CodePudding user response:
One way using lapply
and 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,.)