如何在R中将矩阵分成较小的矩阵? [英] How can I separate a matrix into smaller ones in R?
问题描述
我有以下矩阵
2 4 1
6 32 1
4 2 1
5 3 2
4 2 2
我想根据第3列制作以下两个矩阵
I want to make the following two matrices based on 3rd column
第一
2 4
6 32
4 2
秒
5 3
4 2
我想出了最好的办法,但出现错误
Best I can come up with, but I get an error
x<-cbind(mat [,1],mat [,2])如果mat [,3] = 1
x <- cbind(mat[,1], mat[,2]) if mat[,3]=1
y<-如果mat [,3] = 2则cbind(mat [,1],mat [,2])
y <- cbind(mat[,1], mat[,2]) if mat[,3]=2
推荐答案
如果您有矩阵A,则当第三列为1时,它将获得前两列:
If you have a matrix A, this will get the first two columns when the third column is 1:
A[A[,3] == 1,c(1,2)]
您可以使用它来获取第三列中任何值的矩阵.
You can use this to obtain matrices for any value in the third column.
说明:A [,3] == 1返回一个布尔向量,如果A [i,3]为1,则第i个位置为TRUE.该布尔向量可用于将矩阵索引为:提取我们想要的行.
Explanation: A[,3] == 1 returns a vector of booleans, where the i-th position is TRUE if A[i,3] is 1. This vector of booleans can be used to index into a matrix to extract the rows we want.
免责声明:我对R的经验很少,这是MATLAB式的方法.
Disclaimer: I have very little experience with R, this is the MATLAB-ish way to do it.
这篇关于如何在R中将矩阵分成较小的矩阵?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!