-1

我有一个矩阵,这里通过dput()函数呈现。

Matrix <- structure(list(Int = c(1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 
1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 
1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 
1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 
1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 
1, 1, 1), Time = c(31, 34, 6, 48, 36, 46, 20, 45, 49, 8, 40, 
28, 14, 13, 22, 30, 21, 15, 8, 16, 22, 47, 31, 27, 25, 43, 9, 
24, 20, 7, 48, 10, 48, 18, 44, 26, 43, 39, 44, 41, 20, 36, 43, 
4, 30, 16, 41, 2, 49, 25, 43, 5, 31, 15, 16, 20, 11, 16, 20, 
14, 48, 26, 44, 4, 29, 42, 41, 14, 47, 21, 25, 11, 41, 20, 48, 
35, 4, 42, 19, 8, 34, 23, 39, 25, 11, 29, 24, 31, 9, 20, 6, 45, 
46, 23, 32, 12, 23, 11, 7, 39), Binary = c(1, 1, 1, 1, 1, 1, 
0, 1, 0, 1, 1, 0, 0, 0, 1, 0, 0, 1, 0, 1, 0, 1, 0, 1, 1, 0, 0, 
0, 0, 0, 0, 0, 1, 0, 0, 1, 1, 1, 0, 0, 0, 1, 0, 1, 1, 0, 0, 0, 
1, 0, 1, 0, 1, 0, 0, 0, 1, 1, 1, 0, 1, 0, 1, 0, 0, 1, 0, 0, 1, 
1, 0, 0, 1, 0, 1, 1, 0, 0, 1, 1, 0, 1, 1, 1, 0, 0, 1, 0, 1, 0, 
0, 1, 1, 0, 1, 0, 0, 0, 0, 1), IndID = structure(c(1L, 2L, 3L, 
4L, 1L, 2L, 3L, 4L, 1L, 2L, 3L, 4L, 1L, 2L, 3L, 4L, 1L, 2L, 3L, 
4L, 1L, 2L, 3L, 4L, 1L, 2L, 3L, 4L, 1L, 2L, 3L, 4L, 1L, 2L, 3L, 
4L, 1L, 2L, 3L, 4L, 1L, 2L, 3L, 4L, 1L, 2L, 3L, 4L, 1L, 2L, 3L, 
4L, 1L, 2L, 3L, 4L, 1L, 2L, 3L, 4L, 1L, 2L, 3L, 4L, 1L, 2L, 3L, 
4L, 1L, 2L, 3L, 4L, 1L, 2L, 3L, 4L, 1L, 2L, 3L, 4L, 1L, 2L, 3L, 
4L, 1L, 2L, 3L, 4L, 1L, 2L, 3L, 4L, 1L, 2L, 3L, 4L, 1L, 2L, 3L, 
4L), .Label = c("AAA", "BBB", "CCC", "DDD"), class = "factor")), .Names = c("Int", 
"Time", "Binary", "IndID"), class = "data.frame", row.names = c(NA, 
-100L))

head(Matrix)
  Int Time Binary IndID
1   1   31      1   AAA
2   1   34      1   BBB
3   1    6      1   CCC
4   1   48      1   DDD
5   1   36      1   AAA
6   1   46      1   BBB

矩阵有 100 行和 4 列。数学需要前三列。第 4 列用作 ID。我想将向量矩阵(如下)乘以每个人的较大矩阵的前三列。

这是向量矩阵...

coef <- c(-0.13731791, -0.01122941, 0.65487107)
coef <- as.matrix(coef)
coef

我正在尝试使用下面的代码。

Matrix[Matrix$IndID=="AAA", c(1,2,3)] %*% coef

换句话说:当 IndID 行包含“AAA”时,将 Matrix 的 1:3 列乘以 coef。这会导致以下错误。

"Error in Matrix[Matrix$IndID == "AAA", c(1, 2, 3)] %*% coef : 
  requires numeric/complex matrix/vector arguments"

正如我在其他 SO 帖子中看到的那样,我还尝试使用 & 运算符将两个条件组合到条件列中。该代码和产生的错误如下。

Matrix[,(Matrix$IndID=="AAA") & (c(1,2,3))] %*% coef 

Error in `[.data.frame`(Matrix, , (Matrix$IndID == "AAA") & (c(1, 2, 3))) : 
  undefined columns selected
In addition: Warning message:
In (Matrix$IndID == "AAA") & (c(1, 2, 3)) :
  longer object length is not a multiple of shorter object length

这些数据是我的实际数据的一个样本,我试图将这些函数添加到一个for()包含许多人的更大循环中。

感谢您的任何建议!

4

1 回答 1

0

Matrix是一个数据框,而不是一个矩阵。您可以强制Matrix使用as.matrix(). 尝试:

as.matrix(Matrix[Matrix$IndID=="AAA", c(1,2,3)]) %*% coef
于 2013-11-09T23:30:34.910 回答