Reputation: 41
I am trying to move my list data into a data frame. I want the data frame to look like the image attached. I have tried several methods and I cannot get it. Any help would be appreciated here is my code
symbols <- c('DPZ','SPY','AMD','AAPL','TSLA','MSFT','V', 'WMT', 'SQ','EA','ATVI','AMZN','ROKU', 'PYPL','KO','AXP','CCL','DFS')
getSymbols(symbols, src="yahoo", from='2014-01-01', to='2018-12-31', auto.asign = TRUE)
symb_list <- mget(ls(pattern = paste(symbols, collapse = "|")))
returns_list <- lapply(symb_list, monthlyReturn, subset = NULL, type = 'log', leading = TRUE)
data.frame(t(sapply(returns_list,c)))
Upvotes: 1
Views: 50
Reputation: 887571
We can use rbind
with do.call
do.call(cbind, returns_list)
Or with bind_cols
library(dplyr)
bind_cols(returns_list, .id = 'symbol_name')
If the list
elements are matrix
es, first convert to data.frame
library(purrr)
map_dfc(returns_list, as.data.frame, .id = 'symbol_name')
Or may be, we can do a join
reduce(returns_list, full_join)
Or with Reduce
and merge
out <- Reduce(merge, returns_list)
colnames(out) <- paste0(names(returns_list), colnames(out))
head(out)
# AAPLmonthly.returns AMDmonthly.returns.1 DPZmonthly.returns.2 SPYmonthly.returns.3
#2014-01-31 -0.10438527 -0.11551289 0.013689063 -0.032032798
#2014-02-28 0.04995000 0.07847162 0.113035241 0.044510326
#2014-03-31 0.01975642 0.07775936 -0.026791284 0.003857503
#2014-04-30 0.09476128 0.01975373 -0.034228700 0.006927466
#2014-05-30 0.07019541 -0.02225061 -0.026290421 0.022941215
#2014-06-30 0.02728622 0.04640637 0.008794876 0.015654326
Upvotes: 1