我正在使用消费者价格指数CPI,为了计算它,我必须将指数矩阵与相应的权重相乘:
grossCPI77_10 <- grossIND1977 %*% weights1910/100
grossCPI82_10 <- grossIND1982 %*% weights1910/100
当然我更愿意拥有像以下那样的代码:
grossIND1982 <- replicate(20, cbind(1:61))
grossIND1993 <- replicate(20, cbind(1:61))
weights1910_sc <- c(1:20)
grossIND_list <- mget(ls(pattern = "grossIND...."))
totalCPI <- mapply("*", grossIND_list, weights1910_sc)
问题是它给了我一个1200x20的矩阵。我期望一个正常的矩阵(61x20)向量(20x1)乘法,它应该导致20x1向量?你能解释一下我做错了吗?感谢
答案 0 :(得分:0)
我不确定我是否理解你问题的所有方面(特别是关于应该是colums的内容,应该是什么行,以及应该以何种顺序应用crossproduct),但我会尝试至少涵盖某些方面。请参阅以下代码中的注释,以了解您所做的和您可能想要的内容。我希望它有所帮助,让我知道这是否是你需要的。
#instead of using mget, I recommend to use a list structure
#otherwise you might capture other variables with similar names
#that you do not want
INDlist <- sapply(c("1990", "1991"), function(x) {
#this is how to set up a matrix correctly, check `?matrix`
#I think your combination of cbind and rep did not give you what you wanted
matrix(rep(1:61, 20), nrow = 61)
}, USE.NAMES = TRUE, simplify = F)
weights <- list(c(1:20))
#the first argument of mapply needs to be a function, in this case of two variables
#the body of the function calculates the cross product
#you feed the arguments (both lists) in the following part of mapply
#I have repeated your weights, but you might assign different weights for each year
res <- mapply(function(x, y) {x %*% y}, INDlist, rep(weights, length(INDlist)))
dim(res)
#[1] 61 2
答案 1 :(得分:0)
你的问题的一部分是你没有矩阵而是3D阵列,只有一个单一维度。另一个问题是mapply喜欢尝试将结果组合成一个矩阵,而且常量参数应该通过MoreArgs传递。但实际上,这更适用于lapply。
grossIND1982 <- replicate(20, cbind(1:61))[,1,]
grossIND1993 <- replicate(20, cbind(1:61))[,1,]
weights1910_sc <- c(1:20)
grossIND_list <- mget(ls(pattern = "grossIND...."))
totalCPI <- mapply("*", grossIND_list, MoreArgs=list(e2 = weights1910_sc), SIMPLIFY = FALSE)
totalCPI <- lapply(grossIND_list, "*", e2 = weights1910_sc)