I have these 2 lists.
library(tidyquant)
standin1<-cbind(c("AAPL","JPM"),c("MSFT","FB"))
wantedstocks<-unique(c(standin1))
eeee<-tq_get(wantedstocks,"stock.prices", from = "2015-01-01", to = "2015-01-27")
prices_tbl1<-split(eeee,eeee$symbol)
prices_tbl2<-lapply(prices_tbl1,function(x) xts(x$adjusted,x$date))
prices_tbl3<-do.call(merge,prices_tbl2) #combine xts objects
split_prices_into_years<-split.xts(prices_tbl3,f="weeks",k=1)
jjj<-split_prices_into_years[2:4]
tt<-lapply(jjj, function(x) x[1,])
jjj
[[1]]
FB JPM MSFT AAPL
2015-01-05 77.19 55.15255 42.39050 99.43689
2015-01-06 76.15 53.72248 41.76831 99.44625
2015-01-07 76.15 53.80447 42.29900 100.84071
2015-01-08 78.18 55.00679 43.54335 104.71526
2015-01-09 77.74 54.05040 43.17737 104.82755
[[2]]
FB JPM MSFT AAPL
2015-01-12 76.72 53.58586 42.63753 102.24452
2015-01-13 76.45 53.59496 42.41794 103.15231
2015-01-14 76.28 51.74593 42.05195 102.75926
2015-01-15 74.05 50.08816 41.61278 99.97034
2015-01-16 75.18 50.94437 42.30815 99.19356
[[3]]
FB JPM MSFT AAPL
2015-01-20 76.24 50.74397 42.44539 101.7485
2015-01-21 76.74 50.90794 42.01535 102.5253
2015-01-22 77.65 52.45639 43.12246 105.1925
2015-01-23 77.83 51.62751 43.16822 105.7353
> tt
[[1]]
FB JPM MSFT AAPL
2015-01-05 77.19 55.15255 42.3905 99.43689
[[2]]
FB JPM MSFT AAPL
2015-01-12 76.72 53.58586 42.63753 102.2445
[[3]]
FB JPM MSFT AAPL
2015-01-20 76.24 50.74397 42.44539 101.7485
I want to multiply each column in the jjj list with the respective element in the tt list. So that
FB
2015-01-05 77.19 2015-01-05 5958.296
2015-01-06 76.15 FB 2015-01-06 5878.019
2015-01-07 76.15 (X) 77.19 = 2015-01-07 5878.019
2015-01-08 78.18 2015-01-08 6034.714
2015-01-09 77.74 2015-01-09 6000.751
FB
2015-01-12 76.72 2015-01-12 5958.296
2015-01-13 76.45 FB 2015-01-13 5865.244
2015-01-14 76.28 (X) 76.72 = 2015-01-14 5852.202
2015-01-15 74.05 2015-01-15 5681.116
2015-01-16 75.18 2015-01-16 5767.81
and so on. So i want the output to be on the same form as jjj just with the elements from tt multiplied on like showed above. Any help is really appreciated.
Not terribly pretty, but gets the job done with a loop:
result_list <- list(length=length(jjj))
for(i in 1:length(jjj)) {
result_list[[i]] <- as.matrix(jjj[[i]]) * matrix(rep(tt[[i]], nrow(jjj[[i]])), ncol=ncol(tt[[i]]), byrow=T)
}
or with sapply
, but not any prettier:
sapply(1:length(jjj), function(i) as.matrix(jjj[[i]]) * matrix(rep(tt[[i]], nrow(jjj[[i]])), ncol=ncol(tt[[i]]), byrow=T))