5

我有以下矩阵

2    4    1
6    32   1
4    2    1
5    3    2
4    2    2

我想根据第三列制作以下两个矩阵

第一的

2    4
6    32
4    2

第二

5    3
4    2

我能想到的最好的,但我得到一个错误

x <- cbind(mat[,1], mat[,2]) 如果 mat[,3]=1

y <- cbind(mat[,1], mat[,2]) 如果 mat[,3]=2

4

4 回答 4

12

如果mat是你的矩阵:

mat <- matrix(1:15,ncol=3)
mat[,3] <- c(1,1,1,2,2)
> mat
     [,1] [,2] [,3]
[1,]    1    6    1
[2,]    2    7    1
[3,]    3    8    1
[4,]    4    9    2
[5,]    5   10    2

然后你可以使用split

> lapply( split( mat[,1:2], mat[,3] ), matrix, ncol=2)
$`1`
     [,1] [,2]
[1,]    1    6
[2,]    2    7
[3,]    3    8

$`2`
     [,1] [,2]
[1,]    4    9
[2,]    5   10

lapplyof是必要的matrix,因为 split 删除了使向量成为矩阵的属性,因此您需要将它们重新添加进去。

于 2012-10-25T00:45:43.813 回答
5

还有一个例子:

#test data
mat <- matrix(1:15,ncol=3)
mat[,3] <- c(1,1,1,2,2)

#make a list storing a matrix for each id as components
result <- lapply(by(mat,mat[,3],identity),as.matrix)

完成品:

> result
$`1`
  V1 V2 V3
1  1  6  1
2  2  7  1
3  3  8  1

$`2`
  V1 V2 V3
4  4  9  2
5  5 10  2
于 2012-10-25T02:14:32.750 回答
4

如果你有一个矩阵 A,当第三列为 1 时,这将得到前两列:

A[A[,3] == 1,c(1,2)]

您可以使用它来获取第三列中任何值的矩阵。

说明: A[,3] == 1 返回一个布尔向量,如果 A[i,3] 为 1,则第 i 个位置为 TRUE。此布尔向量可用于索引矩阵以提取行我们想要。

免责声明:我对 R 的经验很少,这是 MATLAB 式的做法。

于 2012-10-25T00:48:15.383 回答
1

这是 pedrosorio 想法的功能版本:

 getthird <- function(mat, idx) mat[mat[,3]==idx, 1:2]
 sapply(unique(mat[,3]), getthird, mat=mat)  #idx gets sent the unique values
#-----------
[[1]]
     [,1] [,2]
[1,]    1    6
[2,]    2    7
[3,]    3    8

[[2]]
     [,1] [,2]
[1,]    4    9
[2,]    5   10
于 2012-10-25T01:03:53.400 回答