Skip to content
Prev 87335 / 398502 Next

elements in each row of a matrix to the left.

Hi Patrick/Jeff,
Not quite.

t(apply(z, 1, sort, na.last=TRUE))

     [,1] [,2] [,3]
[1,]    1    1   NA
[2,]    1    1   NA
[3,]    1    1   NA
[4,]    1   NA   NA
[5,]    1   NA   NA
[6,]   NA   NA   NA

Row 2 is the problem.

I dont want to move all NAs to the end of each row.
I just want to move all of the NAs before the first non-NA element,
if any, to the end of each row.
So in my example, rows 1 and 2 should remain unchanged.

What I have got at the moment is ugly

shiftLeft <- function(z)
{ x <- as.data.frame(t(z)) # work with cols not rows.
  ans <- lapply(x, function(xx) 
  { # get indices of first and last non-NA element
    ind <- which(!is.na(xx))
    ind <- ind[c(1, length(ind))]
    # if all NAs or if first element is non-NA do no work
    if (any(is.na(ind)) || ind[1] == 1) xx else
    { temp <- numeric(length(xx)) ; temp[] <- NA
      # move elements in posns ind[1] to ind[2] to the start
      temp[1:(ind[2]-ind[1]+1)] <- xx[ind[1]:ind[2]]
      temp
    } # if
  }) # lapply
  ans <- as.matrix(data.frame(ans))
  dimnames(ans) <- dimnames(z)
  t(ans)
}
[,1] [,2] [,3]
[1,]    1    1   NA
[2,]    1   NA    1
[3,]   NA    1    1
[4,]   NA   NA    1
[5,]   NA    1   NA
[6,]   NA   NA   NA
     [,1] [,2] [,3]
[1,]    1    1   NA
[2,]    1   NA    1
[3,]    1    1   NA
[4,]    1   NA   NA
[5,]    1   NA   NA
[6,]   NA   NA   NA

I feel that there is probably a shorter vectorised way to do this.
In general, I have matrices (z) with several thousand rows and 
and few hundred columns so vectorisation would help.

Regards,

John.
http://www.R-project.org/posting-guide.html
Visit our website at http://www.ubs.com

This message contains confidential information and is intend...{{dropped}}