R:删除列和行
我得到了以下矩阵:R:删除列和行,r,matrix,R,Matrix,我得到了以下矩阵: mat <- matrix(c(1,2,0,9,8,0,0,0,0),ncol = 3) 我尝试使用行和(mat)==0&&colSums(mat)==0,但找不到它。如果要删除所有和为0的行和所有和为0的列 mat[!!rowSums(mat), !!colSums(mat)] # [,1] [,2] #[1,] 1 9 #[2,] 2 8 但是,如果您想在两个条件都满足的情况下删除,即 mat1 <- matri
mat <- matrix(c(1,2,0,9,8,0,0,0,0),ncol = 3)
我尝试使用
行和(mat)==0&&colSums(mat)==0
,但找不到它。如果要删除所有和为0的行和所有和为0的列
mat[!!rowSums(mat), !!colSums(mat)]
# [,1] [,2]
#[1,] 1 9
#[2,] 2 8
但是,如果您想在两个条件都满足的情况下删除,即
mat1 <- matrix(c(1,2,0,0,9,8,0,0, 0,0,0,0, 4,6,0,0), ncol=4)
indx <- !(!rowSums(mat1) & !colSums(mat1))
mat1[indx,indx]
# [,1] [,2] [,3]
#[1,] 1 9 4
#[2,] 2 8 6
#[3,] 0 0 0
mat1为什么要使用adj
而不是mat
?另外,您应该使用&
而不是&&
。好的,它与&,谢谢!
mat1 <- matrix(c(1,2,0,0,9,8,0,0, 0,0,0,0, 4,6,0,0), ncol=4)
indx <- !(!rowSums(mat1) & !colSums(mat1))
mat1[indx,indx]
# [,1] [,2] [,3]
#[1,] 1 9 4
#[2,] 2 8 6
#[3,] 0 0 0
mat2 <- matrix(c(1,2,0,0,9,8,0,0, 0,0,0,0), ncol=3)
rowSums(mat2)==0 & colSums(mat2)==0
# [1] FALSE FALSE TRUE FALSE
#Warning message:
#In rowSums(mat1) == 0 & colSums(mat1) == 0 :
#longer object length is not a multiple of shorter object length