简体   繁体   English

R中矩阵列表的操作

[英]manipulation of list of matrices in R

I have a list of matrices, generated with the code below 我有一个用下面的代码生成的矩阵列表

a<-c(0,5,0,1,5,1,5,4,6,7)
b<-c(3,1,0,2,4,2,5,5,7,8)
c<-c(5,9,0,1,3,2,5,6,2,7)
d<-c(6,5,0,1,3,4,5,6,7,1)
k<-data.frame(a,b,c,d)
k<-as.matrix(k)
#dimnames(k)<-list(cntry,cntry)

e<-c(0,5,2,2,1,2,3,6,9,2)
f<-c(2,0,4,1,1,3,4,5,1,4)
g<-c(3,3,0,2,0,9,3,2,1,9)
h<-c(6,1,1,1,5,7,8,8,0,2)
l<-data.frame(e,f,g,h)
l<-as.matrix(l)
#dimnames(l)<-list(cntry,cntry)

list<-list(k,l)
names(list)<-2010:2011
list

list
$`2010`
      a b c d
 [1,] 0 3 5 6
 [2,] 5 1 9 5
 [3,] 0 3 2 2
 [4,] 1 2 1 1
 [5,] 5 4 3 3
 [6,] 1 2 2 4
 [7,] 5 5 5 5
 [8,] 4 5 6 6
 [9,] 6 7 2 7
[10,] 7 8 7 1

$`2011`
      e f g h
 [1,] 0 2 3 6
 [2,] 5 0 3 1
 [3,] 2 4 0 1
 [4,] 2 1 2 1
 [5,] 1 1 0 5
 [6,] 2 3 9 7
 [7,] 3 4 3 8
 [8,] 6 5 2 8
 [9,] 9 1 1 0
[10,] 2 4 9 2

In each matrix I would like to delete the rows that are smaller than 1. But when I delete in matrix "2010" the first row (because <1), all other first rows in 2010 and 2011 should be deleted. 在每个矩阵中,我都希望删除小于1的行。但是,当我在矩阵“ 2010”中删除第一行(因为<1)时,应该删除2010和2011中的所有其他第一行。 Then the third row of first column is <1, then all other third columns should be deleted and so on... 然后第一列的第三行是<1,然后应删除所有其他第三列,依此类推...

The result should look like: 结果应如下所示:

      a b c d
 [4,] 1 2 1 1
 [6,] 1 2 2 4
 [7,] 5 5 5 5
 [8,] 4 5 6 6
[10,] 7 8 7 1

$`2011`
      e f g h
 [4,] 2 1 2 1
 [6,] 2 3 9 7
 [7,] 3 4 3 8
 [8,] 6 5 2 8
[10,] 2 4 9 2

We can use rowSums 我们可以使用rowSums

lapply(list, function(x) x[!rowSums(x <1),])

If we need to remove the rows that are common 如果我们需要删除常见的行

ind <- Reduce(`&`, lapply(list, function(x) !rowSums(x < 1)))
lapply(list, function(x) x[ind,])
#      a b c d
#[1,] 1 2 1 1
#[2,] 1 2 2 4
#[3,] 5 5 5 5
#[4,] 4 5 6 6
#[5,] 7 8 7 1

#$`2011`
#     e f g h
#[1,] 2 1 2 1
#[2,] 2 3 9 7
#[3,] 3 4 3 8
#[4,] 6 5 2 8
#[5,] 2 4 9 2

Update 更新

Based on the OP's comments about removing rows where the row is greater than the standard deviation of each columns, 根据OP关于删除行大于每列标准差的行的评论,

lapply(list, function(x) {
       for(i in seq_len(ncol(x))) x <- x[!rowSums(x > sd(x[,i])),]
         x 
   })
# get union of the row index with at least one of the elements less 1 
removed <- Reduce(union, lapply(list, function(x) which(rowSums(x < 1) != 0)))
lapply(list, function(x) x[-removed, ])

$`2010`
     a b c d
[1,] 1 2 1 1
[2,] 1 2 2 4
[3,] 5 5 5 5
[4,] 4 5 6 6
[5,] 7 8 7 1

$`2011`
     e f g h
[1,] 2 1 2 1
[2,] 2 3 9 7
[3,] 3 4 3 8
[4,] 6 5 2 8
[5,] 2 4 9 2

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM