0

I would like to cbind dataframes with conditional to insert "NA" in the subsequent rows. I applied splitin a dataframe dfall and got:

My df[[1]]:

chr  start  end    N01   N04   N05 
 1    30    40     30    20     29 

My df[[2]]:

 chr  start  end    N01   N02   N03 
  2     40    50    30    20     29 

I would like to get:

 chr  start  end    N01.a   N04   N05  N01.b   N02  N03 
  1     30    40     30    20     29    NA     NA    NA
  2     40    50     NA    NA     NA    30     20    29   

I tried without success:

labelallgenes <- dfall[1:2,]
dfall.split<- split(dfall, 1:nrow(dfall))
for(k in length(dfall.split)){
dfk <- dfall.split[[k]]
labelallgenes <- cbind.fill(labelallgenes, dfk, fill=NA)}

Some idea? Thank you very much.

thelatemail
  • 91,185
  • 12
  • 128
  • 188
user2120870
  • 869
  • 4
  • 16

1 Answers1

0

Assuming that 'df' is a list, we can use 'Reduce' and 'merge' the list elements together.

Reduce(function(...) merge(..., by=c('chr', 'start', 'end'), all=TRUE), df)
#   chr start end N01.x N04 N05 N01.y N02 N03
#1   1    30  40    30  20  29    NA  NA  NA
#2   2    40  50    NA  NA  NA    30  20  29

data

df <- list(structure(list(chr = 1L, start = 30L, end = 40L, N01 = 30L, 
N04 = 20L, N05 = 29L), .Names = c("chr", "start", "end", 
"N01", "N04", "N05"), class = "data.frame", row.names = c(NA, 
-1L)), structure(list(chr = 2L, start = 40L, end = 50L, N01 = 30L, 
N02 = 20L, N03 = 29L), .Names = c("chr", "start", "end", 
"N01", "N02", "N03"), class = "data.frame", row.names = c(NA, -1L)))
akrun
  • 874,273
  • 37
  • 540
  • 662
  • That´s is completely righ. However, in my real analysis I can´t come back to the `df`. There exist some way to deal with each `k` separately (with some comand inside each loop turn) to finish in equal result? – user2120870 Mar 30 '15 at 05:13
  • @user2120870 I think it would help if you show reproducible example. http://stackoverflow.com/questions/5963269/how-to-make-a-great-r-reproducible-example – akrun Mar 30 '15 at 07:59