I wonder if someone can explain me how can i set type for each variable in my dataframe.
I made up a function to call quotes from yahoo API as JSON and i've rbind each of them into a dataframe called portfolio. Unfortunantely data are very raw and all comes as characters.
I'm asking you if there is a simple way in which r can automatically store values as numeric or character without setting each variable through the dataframe.
Here I paste you my script :
library(jsonlite)
# function that sets all NULL values to NA
nullToNA <- function(x) {
x[sapply(x, is.null)] <- NA
return(x)
}
# function that gets Quotes from Yahoo API
getQuote <- function(ticker) {
path <- paste("https://query.yahooapis.com/v1/public/yqlq=select%20*%20from%20yahoo.finance.quotes%20where%20symbol%20in%20(%22",ticker,"%22)&format=json&env=store%3A%2F%2Fdatatables.org%2Falltableswithkeys&callback=", sep="")
stock <- fromJSON(path, flatten = TRUE)
q <- stock$query$results$quote
q <- nullToNA(q)
}
# define the tickers to include in portfolio
tickers <- c("AAPL","GOOG", "AMZN")
# portfolio construction
portfolio <- c()
for (ticker in tickers){
portfolio <- rbind(portfolio, getQuote(ticker))
}
portfolio < unlist(portfolio)
portfolio <- data.frame(portfolio, stringsAsFactors = FALSE)
This leads to a dataframe of 3 obs and 83 variables but as i run str() on portfolio i see that each of them is a list instead of character or numeric. Is there a way to fix it?