structure(c(-13.2728762809309, 1.4589335335744, 0.484047921906014,
0.961191008159664, 9.8283305061549, 0.719751064235688, -12.9935586779498,
1.54850677442014, -13.1416306849761, 1.45529160258359), .Dim = c(2L,
5L), .Dimnames = list(c("(Intercept)", "PJMPWr[, x]"), NULL))
需要使用这些系数进行预测,并使用以下方法创建新矩阵: c(20,30,40)等于-13.2728 * 20 + 1.4589,-13.2728 * 30 + 1.4589,-13.2728 * 40 +1.4589 ..
答案 0 :(得分:2)
你可以这样做的一种方式是:
(mat <- structure(c(-13.2728762809309, 1.4589335335744, 0.484047921906014, 0.961191008159664, 9.8283305061549,
0.719751064235688, -12.9935586779498, 1.54850677442014, -13.1416306849761, 1.45529160258359),
.Dim = c(2L, 5L), .Dimnames = list(c("(Intercept)", "PJMPWr[, x]"), NULL)))
# [,1] [,2] [,3] [,4] [,5]
# (Intercept) -13.272876 0.4840479 9.8283305 -12.993559 -13.141631
# PJMPWr[, x] 1.458934 0.9611910 0.7197511 1.548507 1.455292
(vec <- c(20, 30, 40))
# [1] 20 30 40
t(mat[2,] %*% t(vec) + mat[1,])
# [,1] [,2] [,3] [,4] [,5]
# [1,] 15.90579 19.70787 24.22335 17.97658 15.96420
# [2,] 30.49513 29.31978 31.42086 33.46164 30.51712
# [3,] 45.08447 38.93169 38.61837 48.94671 45.07003
一些说明:
mat[1,]
和mat[2,]
是单行,因此默认行为是它们被强制为1维向量。 (见help(`[`)
。)t(vec)
将向量vec
转换为1 x 3
矩阵(请参阅help(t)
。)mat[2,] %*% t(vec)
中,向量mat[2,]
被视为5 x 1
矩阵,以使两个参数一致。 (参见help(`%*%`)
。)因此,乘法的结果是5 x 3
矩阵。mat[1,]
添加到5 x 3
矩阵时,向量的元素将沿着矩阵的列进行回收。3 x 5
矩阵。答案 1 :(得分:1)
您可以使用mapply
尝试以下内容:
mapply(function(x, y) x[2] * y + x[1],
#your coefficients
as.data.frame(mat),
#your vector replicated 5 times
replicate(5, c(20, 30, 40), simplify = FALSE))
# V1 V2 V3 V4 V5
#[1,] 15.90579 19.70787 24.22335 17.97658 15.96420
#[2,] 30.49513 29.31978 31.42086 33.46164 30.51712
#[3,] 45.08447 38.93169 38.61837 48.94671 45.07003