我有以下矩阵
2 4 1
6 32 1
4 2 1
5 3 2
4 2 2
Run Code Online (Sandbox Code Playgroud)
我想基于第3列制作以下两个矩阵
第一
2 4
6 32
4 2
Run Code Online (Sandbox Code Playgroud)
第二
5 3
4 2
Run Code Online (Sandbox Code Playgroud)
我能想出最好的,但是我收到了错误
x < - cbind(mat [,1],mat [,2])如果mat [,3] = 1
y < - cbind(mat [,1],mat [,2])如果mat [,3] = 2
Ari*_*man 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
Run Code Online (Sandbox Code Playgroud)
然后你可以使用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
Run Code Online (Sandbox Code Playgroud)
该lapply的matrix,因为分裂下降,使一个向量矩阵的属性是必要的,所以你需要将它们添加回.
又一个例子:
#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)
Run Code Online (Sandbox Code Playgroud)
最终产品:
> 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
Run Code Online (Sandbox Code Playgroud)
如果你有一个矩阵 A,当第三列为 1 时,这将获得前两列:
A[A[,3] == 1,c(1,2)]
Run Code Online (Sandbox Code Playgroud)
您可以使用它来获取第三列中任何值的矩阵。
解释:A[,3] == 1 返回一个布尔向量,其中如果 A[i,3] 为 1,则第 i 个位置为 TRUE。该布尔向量可用于索引矩阵以提取行我们想要。
免责声明:我对 R 的经验很少,这是 MATLAB 式的方法。