我需要对一个矩阵进行子集化,只保留总和大于 0 的列,并保留总和大于 0 的行。
这是我最好的尝试,但它不起作用:
clean_data <- data [,colSums(data)!=0] & [rowSums(data)!=0,]
Given this matrix:
0 1 0 2 3;
0 0 0 0 1;
0 0 0 0 0;
1 0 0 2 0;
I need this matrix:
0 1 2 3;
0 0 0 1;
1 0 2 0;
另外,现在怎样才能制作平方矩阵?相同数量的列和行,即所有列名都出现在行中,反之亦然)。
要获得您“需要”的矩阵,请尝试以下操作:
> dat <- matrix(
data = c(0,0,0,1, 1,0,0,0,0,0,0,0,2,0,0,2,3,1,0,0),
nrow = 4,
ncol = 5
)
> dat
[,1] [,2] [,3] [,4] [,5]
[1,] 0 1 0 2 3
[2,] 0 0 0 0 1
[3,] 0 0 0 0 0
[4,] 1 0 0 2 0
> dat[rowSums(dat) > 0, colSums(dat) > 0]
[,1] [,2] [,3] [,4]
[1,] 0 1 2 3
[2,] 0 0 0 1
[3,] 1 0 2 0
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句