Rearrange data frame in R

The following R code generates a fragment from the data frame I'm currently working with:

rep1 <- c("20/02/01","23/03/02") rep2 <- c(NA, "03/05/02") rep3 <- c("16/04/01",NA) rep4 <- c(NA,"12/02/03") data <- data.frame(rep1 = rep1, rep2 = rep2, rep3 = rep3, rep4 = rep4) 

The data frame generated by the code is as follows:

  rep1 rep2 rep3 rep4 1 20/02/01 <NA> 16/04/01 <NA> 2 23/03/02 03/05/02 <NA> 12/02/03 

I would like to change this data frame so that it looks like this:

  rep1 rep2 rep3 rep4 1 20/02/01 16/04/01 <NA> <NA> 2 23/03/02 03/05/02 12/02/03 <NA> 

That is, for each line, I would like to replace each NA with the next line in the line, until only NA is left in the line.

A true data frame consists of several thousand rows, so this can mean many late hours in the office.

If anyone could tell me how to do this in R, I would be very grateful!

+4
source share
2 answers

I'm not sure I understand, but it looks like you want to move NA to the end of the columns? Here is one way (quick, maybe cleaner):

 > d <- data.frame(rbind(c(1, 2, NA, 4, NA, 6), c(NA, 2, 3, 4, 5, 6))) > d X1 X2 X3 X4 X5 X6 1 1 2 NA 4 NA 6 2 NA 2 3 4 5 6 > t(apply(d, 1, function(x) c(x[!is.na(x)], rep(NA, sum(is.na(x)))))) [,1] [,2] [,3] [,4] [,5] [,6] [1,] 1 2 4 6 NA NA [2,] 2 3 4 5 6 NA 

According to your data:

 > t(apply(data, 1, function(x) c(x[!is.na(x)], rep(NA, sum(is.na(x)))))) [,1] [,2] [,3] [,4] [1,] "20/02/01" "16/04/01" NA NA [2,] "23/03/02" "03/05/02" "12/02/03" NA 
+1
source

Vince's next suggestion, but perhaps a little cleaner:

 t(apply(d, 1, function(x) x[order(x)])) 
0
source

All Articles