R矩阵列表 - 根据值和列名更改值

时间:2016-12-28 16:28:57

标签: r

我有一个矩阵列表。如果它们具有某个列名,我想将矩阵的负元素更改为零。在下面的示例中,我想设置具有列名称的元素' a'等于零。

> set.seed(4)
> z<-lapply(1:3, function(x) matrix(sample(-10:10,20, replace=T), nrow=4))
> z<-lapply(z, function(x) {colnames(x)<-c("a","c","b","a","b");x})
> z
[[1]]
       a  c  b  a  b
[1,]   2  7  9 -8 10
[2,] -10 -5 -9 10  2
[3,]  -4  5  5 -2 10
[4,]  -5  9 -4 -1  5

[[2]]
      a c  b  a   b
[1,]  5 3  0  8  -1
[2,] 10 7  1  3   3
[3,]  0 0  1  0  -2
[4,]  0 7 -5 10 -10

[[3]]
      a  c  b  a  b
[1,]  9  8  5  8 -7
[2,] -5 -9  1  6 -7
[3,]  1  8 -2  7  8
[4,] -7  8  5 -2  5

这就是我想要做的:

[[1]]
       a  c  b  a  b
[1,]   2  7  9  0 10
[2,]   0 -5 -9 10  2
[3,]   0  5  5  0 10
[4,]   0  9 -4  0  5

[[2]]
      a c  b  a   b
[1,]  5 3  0  8  -1
[2,] 10 7  1  3   3
[3,]  0 0  1  0  -2
[4,]  0 7 -5 10 -10

[[3]]
      a  c  b  a  b
[1,]  9  8  5  8 -7
[2,]  0 -9  1  6 -7
[3,]  1  8 -2  7  8
[4,]  0  8  5  0  5

我尝试了这个,但似乎搞砸了其他元素。

> keeper<-which(colnames(z[[1]])=="a")
> lapply(z, function(x) {x[x[,keeper]<0]<-0;x})
[[1]]
     a  c b  a  b
[1,] 2  0 9  0 10
[2,] 0 -5 0 10  0
[3,] 0  0 0  0  0
[4,] 0  0 0  0  0

[[2]]
      a c  b  a   b
[1,]  5 3  0  8  -1
[2,] 10 7  1  3   3
[3,]  0 0  1  0  -2
[4,]  0 7 -5 10 -10

[[3]]
     a  c  b a  b
[1,] 9  8  5 8 -7
[2,] 0 -9  0 6  0
[3,] 1  8 -2 7  8
[4,] 0  0  0 0  0

1 个答案:

答案 0 :(得分:1)

以下是使用pmax进行替换的替代方案。

lapply(z, function(x) {x[, colnames(x) == "a"] <- pmax(x[, colnames(x) == "a"], 0); x})
[[1]]
     a  c  b  a  b
[1,] 2  7  9  0 10
[2,] 0 -5 -9 10  2
[3,] 0  5  5  0 10
[4,] 0  9 -4  0  5

[[2]]
      a c  b  a   b
[1,]  5 3  0  8  -1
[2,] 10 7  1  3   3
[3,]  0 0  1  0  -2
[4,]  0 7 -5 10 -10

[[3]]
     a  c  b a  b
[1,] 9  8  5 8 -7
[2,] 0 -9  1 6 -7
[3,] 1  8 -2 7  8
[4,] 0  8  5 0  5