user59419
user59419

Reputation: 993

Change the column of same values to column of all zeros in R

Assume I have a list called: LS1 and within the list I have 20 matrix of 100 by 5. Now some columns might have just one value repeated like one column is all 100. I want to make these all 100 to all zeros. I can write a for loop to do that but I want to do it more efficiently with lapply and apply. For example one example of this matrix is

1 2 3 4 5
1 3 4 5 6
1 5 6 8 9

I want the first column which is all ones is changed to all zeros.

This is what I have done :

A= lapply(LS1, function(x) {apply(x,2,function(x1)  {if(max(x1)== min(x1)) 
    {0}}}

but this makes all the values NULL. Can anyone suggest doing this with lapply and apply?

Upvotes: 0

Views: 286

Answers (2)

Zhiqiang Wang
Zhiqiang Wang

Reputation: 6769

This is my solution:

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
> A
  a b c d e
1 0 2 4 5 0
2 0 3 5 6 0
3 0 5 8 9 0

If use sapply:

A = sapply(df, function(x)  x = (max(x)!=min(x))*x)
A
     a b c d e
[1,] 0 2 4 5 0
[2,] 0 3 5 6 0
[3,] 0 5 8 9 0

Upvotes: 0

Cole
Cole

Reputation: 11255

This should work, especially for integer matrices.

lapply(lst, 
       function(mat) {
          all_dupes = apply(mat, 2, function(x) length(unique(x)) ==1)
          mat[, all_dupes]  = 0L
          return(mat)
         }
)

Upvotes: 1

Related Questions