Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/r/70.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
将R中相同值的列更改为全零列_R_List_For Loop_Apply_Lapply - Fatal编程技术网

将R中相同值的列更改为全零列

将R中相同值的列更改为全零列,r,list,for-loop,apply,lapply,R,List,For Loop,Apply,Lapply,假设我有一个名为:LS1的列表,在这个列表中我有20个100乘5的矩阵。现在有些列可能只重复一个值,就像一列都是100一样。我想把这些都变成100到0。我可以编写一个for循环来实现这一点,但我希望通过lappy和apply更有效地实现这一点。例如,该矩阵的一个示例是 1 2 3 4 5 1 3 4 5 6 1 5 6 8 9 我想把第一列全1改为全0 这就是我所做的: A= lapply(LS1, function(x) {apply(x,2,function(x1) {if(max(x1

假设我有一个名为:LS1的列表,在这个列表中我有20个100乘5的矩阵。现在有些列可能只重复一个值,就像一列都是100一样。我想把这些都变成100到0。我可以编写一个for循环来实现这一点,但我希望通过lappy和apply更有效地实现这一点。例如,该矩阵的一个示例是

1 2 3 4 5
1 3 4 5 6
1 5 6 8 9
我想把第一列全1改为全0

这就是我所做的:

A= lapply(LS1, function(x) {apply(x,2,function(x1)  {if(max(x1)== min(x1)) 
    {0}}}
但这会使所有值都为空。有人能建议用Lappy和apply这样做吗?

这是我的解决方案:

df <- data.frame(a = c(1, 1, 1), 
               b = c(2, 3, 5), 
               c = c(4, 5, 8),
               d = c(5, 6, 9), 
               e = c(5, 5, 5))

A = data.frame(lapply(df, function(x)  x = (max(x)!=min(x))*x ))
A
如果使用
sapply

A = sapply(df, function(x)  x = (max(x)!=min(x))*x)
A

这应该是可行的,特别是对于整数矩阵

lapply(lst, 
       function(mat) {
          all_dupes = apply(mat, 2, function(x) length(unique(x)) ==1)
          mat[, all_dupes]  = 0L
          return(mat)
         }
)
     a b c d e
[1,] 0 2 4 5 0
[2,] 0 3 5 6 0
[3,] 0 5 8 9 0
lapply(lst, 
       function(mat) {
          all_dupes = apply(mat, 2, function(x) length(unique(x)) ==1)
          mat[, all_dupes]  = 0L
          return(mat)
         }
)