Search code examples
rdataframemergerbindcbind

Merging multiple data frames by pasting alternative rows


I have spatial weather data of UK in Ascii text format for 7 years (each file/dataframe have monthly data of one year - 12 columns and 52201 rows as each row represents one location). I want to merge data frames with alternative rows - 1st row of data frame 1 then 1st row of data frame 2 till 1st row of data frame 7 then 2nd row of data frame 1 till 2nd row of data frame 7 and continue ....

  V1    V2    V3    V4    V5    V6    V7    V8    V9   V10   V11   V12
-1199 -1199 -1199 -1199 -1199 -1199 -1199 -1199 -1199 -1199 -1199 -1199
-1299 -1299 -1299 -1299 -1299 -1299 -1299 -1299 -1299 -1299 -1299 -1299
-1399 -1399 -1399 -1399 -1399 -1399 -1399 -1399 -1399 -1399 -1399 -1399
-9999 -9999 -9999 -9999 -9999 -9999 -9999 -9999 -9999 -9999 -9999 -9999
-9999 -9999 -9999 -9999 -9999 -9999 -9999 -9999 -9999 -9999 -9999 -9999

Here is my code:

n1<-read.table("data/y1call.txt", sep="")
n2<-read.table("data/y2call.txt", sep="")
n3<-read.table("data/y3call.txt", sep="")
c<-rbind(n1,n2,n3)
merge(n1,n2,n3)

I have tried merge, rbind, cbind but all failed.


Solution

  • You can create a new column representing the rownames in each data frame, and sort on that variable after you rbind, i.e.

    ddf_all <- do.call(rbind, lapply(list(df1, df2, df3), function(i)transform(i, new = rownames(i))))
    ddf_all[order(ddf_all$new),]
    

    which gives,

       v1 v2 new
    1   1  6   1
    6  11 16   1
    11 21 26   1
    2   2  7   2
    7  12 17   2
    12 22 27   2
    3   3  8   3
    8  13 18   3
    13 23 28   3
    4   4  9   4
    9  14 19   4
    14 24 29   4
    5   5 10   5
    10 15 20   5
    15 25 30   5
    

    DATA:

    df1 <- data.frame(v1 = c(1, 2, 3, 4, 5), V2 = c(6, 7, 8, 9, 10))
    df2 <- data.frame(v1 = c(11, 12, 13, 14, 15), v2 = c(16, 17, 18, 19, 20))
    df3 <- data.frame(v1 = c(21, 22, 23, 24, 25), v2 = c(26, 27, 28, 29, 30))