我有这两个清单。
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
我想将jjj列表中的每一列与tt列表中的相应元素相乘。以便
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
等等。所以我希望输出与jjj相同,只是将tt的元素乘以上面所示的形式。任何帮助都非常感谢。
最佳答案
不是很漂亮,但是可以通过循环完成工作:
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)
}
或使用
sapply
,但不是更漂亮:sapply(1:length(jjj), function(i) as.matrix(jjj[[i]]) * matrix(rep(tt[[i]], nrow(jjj[[i]])), ncol=ncol(tt[[i]]), byrow=T))
关于r - 列表中的元素与同一时期内另一个列表中的列相乘,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/52396410/