R function for sorting NAs and data in each row of a Matrix

by Chris Fariss

# —– naSortMatrix function —————————— #
# —– by Chris Fariss ———————————— #
#
# Takes a data frame or matrix as an argument
# and returns another matrix after moving any NAs
# within each matrix row to the right of the data
# in that row without changing the order of the
# data. Also calculates the time taken to complete
# the sort and saves it as a global variable:
# naSortMatrix.time
#
# Just copy and paste this during an R session to
# use the function
#
# ——————————————————– #

naSortMatrix <- function(x){
# time at start of function
d1 <- Sys.time()

# convert data.frame to matrix
data <- as.matrix(x)

# transpose matrix and then turn it into a vector
data.vector <- c(t(data))

# create a matrix of observation IDs and then transponse and turn it into a vector also
index <- c(t(matrix(c(1:nrow(data)), nrow=nrow(data), ncol=ncol(data), byrow=F)))

# combine the index vector and data vector into a long matrix
data.long <- cbind(index, data.vector)

# sort long matrix by index and the data vector. this will place all of the NAs at
# the end of each panel in the long matrix and keep the IDs from changing position
newdata <- data.long[order(data.long[,1], data.long[,2]),]

# transform the long matrix back into a wide matrix with the same observation order
out <- matrix(newdata[,2], nrow=nrow(data), byrow=T)

# calculate time at end and the difference between time at start as a global variable
d2 <- Sys.time()
naSortMatrix.time <<- d2-d1

# return the sorted matrix
return(out)
}

# —– end file ————————————— #

Advertisements

One response to “R function for sorting NAs and data in each row of a Matrix

  1. “R function for sorting NAs and data in each row of a Matrix | Human
    Nature Group” was a pretty nice posting, . I hope you
    keep posting and I will continue following! Thanks for
    your time -Augustina

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s