如何删除R中某些列中包含零的矩阵行

时间:2013-07-03 13:54:59

标签: r matrix

我有一个像下面这样的矩阵,我需要删除列1:10或列11:20中全部为零的行。因此,例如在我的数据中,应该删除第8行,因为列1:10中的所有值都为零。 我有这个代码,但它不起作用:

> dput(mat)
structure(c(6L, 645L, 897L, 13L, 278L, 384L, 200L, 0L, 0L, 133L, 
8L, 415L, 685L, 7L, 208L, 239L, 150L, 0L, 2L, 85L, 7L, 600L, 
850L, 17L, 337L, 358L, 172L, 0L, 0L, 150L, 0L, 341L, 396L, 7L, 
252L, 222L, 88L, 0L, 0L, 84L, 6L, 799L, 978L, 24L, 534L, 464L, 
156L, 0L, 0L, 216L, 5L, 306L, 418L, 7L, 238L, 215L, 46L, 0L, 
0L, 109L, 4L, 292L, 378L, 4L, 237L, 159L, 64L, 0L, 0L, 74L, 7L, 
401L, 579L, 8L, 305L, 281L, 107L, 0L, 0L, 133L, 9L, 821L, 854L, 
31L, 525L, 422L, 150L, 0L, 0L, 182L, 5L, 796L, 980L, 25L, 519L, 
491L, 148L, 0L, 0L, 213L, 3L, 580L, 753L, 11L, 246L, 299L, 166L, 
0L, 1L, 102L, 5L, 364L, 503L, 14L, 201L, 244L, 115L, 0L, 0L, 
67L, 7L, 406L, 670L, 13L, 258L, 227L, 139L, 0L, 0L, 102L, 7L, 
846L, 998L, 16L, 440L, 444L, 170L, 0L, 1L, 233L, 6L, 574L, 630L, 
6L, 211L, 231L, 132L, 0L, 0L, 107L, 15L, 866L, 1074L, 35L, 535L, 
507L, 188L, 0L, 1L, 193L, 8L, 817L, 1078L, 31L, 493L, 532L, 183L, 
0L, 0L, 258L, 8L, 426L, 635L, 17L, 354L, 282L, 120L, 0L, 0L, 
134L, 3L, 432L, 597L, 6L, 197L, 230L, 133L, 1L, 0L, 95L, 10L, 
493L, 727L, 30L, 425L, 341L, 151L, 0L, 0L, 133L), .Dim = c(10L, 
20L), .Dimnames = list(c("1", "2", "3", "4", "5", "6", "7", "8", 
"9", "10"), c("V2", "V3", "V4", "V5", "V6", "V7", "V8", "V9", 
"V10", "V11", "V12", "V13", "V14", "V15", "V16", "V17", "V18", 
"V19", "V20", "V21")))

test <- apply(mat, 1,function(row)all(mat[row,1:10]==0) || all(mat[row,11:20]==0) )
mat <- mat[!test,]

2 个答案:

答案 0 :(得分:5)

您不需要apply

mat[rowSums(abs(mat[,1:10]))>0 & rowSums(abs(mat[,11:20]))>0,]

答案 1 :(得分:4)

apply逐行遍历矩阵。请改用:

test <- apply(mat, 1,function(x) all(x[1:10]==0) | all(x[11:20]==0) )