Search code examples
rrowzerocol

Removing zeros without removing entire row or col - R


Is there any way to make the first column start by the first positive value? Suppose I have a data like this

enter image description here

and I want it to look like this:

enter image description here

Obviously my data is much bigger and to do it manually it's very tedious. I've search about this, but can only find ways to remove rows or columns based on zeros.


Solution

  • You can exclude elements equal to zero and adapt the length row-wise.

    t(mapply(`length<-`, apply(m, 1, function(x) x[x != 0]), ncol(m)))
    #      [,1] [,2] [,3] [,4] [,5]
    # [1,]    1    7    9    4   NA
    # [2,]    3    6   NA   NA   NA
    # [3,]    1    6    6    4    3
    # [4,]    7   NA   NA   NA   NA
    # [5,]    4    3    1    8   NA
    

    If your data is a data frame,

    d <- as.data.frame(m)
    

    you may do:

    setNames(as.data.frame(t(mapply(`length<-`, apply(d, 1, function(x) x[x != 0]), ncol(d)))),
             names(d))
    #   V1 V2 V3 V4 V5
    # 1  1  7  9  4 NA
    # 2  3  6 NA NA NA
    # 3  1  6  6  4  3
    # 4  7 NA NA NA NA
    # 5  4  3  1  8 NA
    

    Data

    m <- matrix(c(0, 0, 1, 0, 0,
                  1, 0, 6, 0, 4,
                  7, 0, 6, 0, 3,
                  9, 3, 4, 0, 1,
                  4, 6, 3, 7, 8), 5)