[英]R Multiplying a list of lists with a vector
I have a dataframe with 1 column consisting of 10 lists each with a varying number of elements. 我有一个包含1列的数据框,该列由10个列表组成,每个列表具有不同数量的元素。 I also have a vector with 10 different values in it (10 integers). 我也有一个向量,其中有10个不同的值(10个整数)。
I want to take the "sumproduct" of each 10 lists with its corresponding vector value, and end up with 10 values. 我想取每个10个列表的“和积”及其对应的向量值,最后得到10个值。
Value 1 = sumproduct(First list, First vector value)
Value 2 = sumproduct(Second list, Second vector value)
etc...
Final_Answer <- c(Value 1, Value 2, ... , Value 10)
I have a function that generates the dataframe containing lists of numbers representing years. 我有一个函数来生成包含表示年份的数字列表的数据框。 The dataframe is contructed using a loop to generate each value then rowbinding the value together with the dataframe. 使用循环构造数据帧以生成每个值,然后将该值与数据帧进行行绑定。
Time_Function <- function(Maturity)
{for (i in 0:Count)
{x<-as.numeric(((as.Date(as.Date(Maturity)-i*365)-Start_Date)/365)
Time <- rbind(Time, data.frame(x))}
return((Time))
}
The result is this: 结果是这样的:
http://pastebin.com/J6phR2hv http://pastebin.com/J6phR2hv
http://i.imgur.com/Sf4mpA5.png http://i.imgur.com/Sf4mpA5.png
If my vector looks like [1,2,3,4...,10], I want the output to be: Final Answer = [(1*1.1342466 + 1*0.6342466 + 1* 0.1342466), (2*1.3835616 + 2*0.8835616 + 2*0.3835616), ... , ( ... +10*0.0630137)] 如果我的向量看起来像[1,2,3,4 ...,10],我希望输出为:最终答案= [(1 * 1.1342466 + 1 * 0.6342466 + 1 * 0.1342466),(2 * 1.3835616 + 2 * 0.8835616 + 2 * 0.3835616),...,(... ... + 10 * 0.0630137)]
Assuming you want to multiply each value in the list by the respective scalar and then add it all up, here is one way to do it. 假设您想将列表中的每个值乘以各自的标量,然后将其全部相加,这是一种实现方法。
list1 <- mapply(rep, 1:10, 10:1)
vec1 <- 1:10
df <- data.frame( I(list1), vec1)
df
list1 vec1
1 1, 1, 1,.... 1
2 2, 2, 2,.... 2
3 3, 3, 3,.... 3
4 4, 4, 4,.... 4
5 5, 5, 5,.... 5
6 6, 6, 6,.... 6
7 7, 7, 7, 7 7
8 8, 8, 8 8
9 9, 9 9
10 10 10
mapply(df$list1, df$vec1, FUN = function(x, y) {y* sum(x)})
[1] 10 36 72 112 150 180 196 192 162 100
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.