1

I know this might be a peculiar question, but:

I have a data frame which looks more or less like this:

    t1 t2 t3 t4
o1  NA  1  1  1
o2  1  NA NA NA
o3  NA NA 1  1
o4  1  1  NA NA
o5  1  1  1  1

I want to reorder it so it looks like this:

    t1 t2 t3 t4
o3  NA NA 1  1
o1  NA  1  1  1
o5  1  1  1  1
o4  1  1  NA NA
o2  1  NA NA NA

So as you can se if we go from the bottom left corner towards the upper right corner there's this "tunnel" (path, whatever). The bottom row contains the most NAs from the right, the middle rows have none and the top rows are the ones with NAs on the left (the top one having the most NAs).

Is there any easy (or at least not too hard) way to do this? Also the data frame is relatively big (400x3300). Column and row names must be perserved. I want to then take this data frame and make a heat map.

2
  • Do your non-NA values vary? When you say you want to retain your row names, how does your example do this?
    – mnel
    Jun 4, 2013 at 7:01
  • yes nonNA values can vary. I mean I want the resulting data.frame/matrix/whatever to have each row properly labeled. As you can see in the example the row order changed but still each row is using it's original label - so basically the labels moved with the rows. Jun 4, 2013 at 7:03

2 Answers 2

2

Assuming there are no rows with NAs only in the middle:

DF <- read.table(text="    t1 t2 t3 t4
o1  NA  1  1  1
o2  1  NA NA NA
o3  NA NA 1  1
o4  1  1  NA NA
o5  1  1  1  1", header=TRUE)

DF1 <- DF[is.na(DF$t1),]
DF2 <- DF[rowSums(is.na(DF))==0,]
DF3 <- DF[is.na(DF$t4),]

DF1 <- DF1[order(-rowSums(is.na(DF1))),]
DF3 <- DF3[order(rowSums(is.na(DF3))),]

DF <- rbind(DF1,DF2,DF3)

#    t1 t2 t3 t4
# o3 NA NA  1  1
# o1 NA  1  1  1
# o5  1  1  1  1
# o4  1  1 NA NA
# o2  1 NA NA NA
1
  • awesome, I was thinking about doing something exactly like this but I was lacking some details (choosing the rows with NAs and ordering by rowSums), thanks! :-) Jun 4, 2013 at 7:16
2
d <- data.frame(t1=c(NA, 1, NA, 1, 1),
                t2=c(1, NA, NA, 1, 1),
                t3=c(1, NA,  1, NA,1),
                t4=c(1, NA,  1, NA,1))
row.names(d) <- c("o1", "o2", "o3", "o4", "o5")
d
   t1 t2 t3 t4
o1 NA  1  1  1
o2  1 NA NA NA
o3 NA NA  1  1
o4  1  1 NA NA
o5  1  1  1  1


first1 <- apply(d, 1, function(x) {which(x == 1)[1] })
last1  <- apply(d, 1, function(x) {rev(which(x == 1))[1] })

d[order(first1, last1, decreasing=TRUE),]

   t1 t2 t3 t4
o3 NA NA  1  1
o1 NA  1  1  1
o5  1  1  1  1
o4  1  1 NA NA
o2  1 NA NA NA

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.