Search code examples
rdataframemergedplyrdata-analysis

I tried many codes to merge meltiple data frames together in R, but always get error


Update: problem sloved, I shouldn't name the variable name as '2013'

I have some data frames, I want to merge them together, but always get an error. I want to merge them by the variable ('Date' and 'Time'), each data frame has the same value for 'Date' and 'Time'.

This is what I have tried:

> list2013 <- list(data1, data2, data3, data4, data5, data6, data7)
> 2013 <- Reduce(function(x, y) merge(x, y, all = TRUE), list2013, accumulate = FALSE)

Error in 2013 <- Reduce(function(x, y) merge(x, y, all = TRUE), list2013,  
:  invalid (do_set) left-hand side to assignment

The data frames look like this:

head(data1)
        Date  Time  Value_1
1 01/01/2013 00:00     84
2 01/01/2013 00:15     71
3 01/01/2013 00:30     73
4 01/01/2013 00:45     73
5 01/01/2013 01:00     73
6 01/01/2013 01:15     80

 head(data2)
        Date  Time  Value_2
1 01/01/2013 00:00      38
2 01/01/2013 00:15      29
3 01/01/2013 00:30      27
4 01/01/2013 00:45      32
5 01/01/2013 01:00      36
6 01/01/2013 01:15      40

head(data3)
        Date  Time  Value_3
1 01/01/2013 00:00      23
2 01/01/2013 00:15      13
3 01/01/2013 00:30      11
4 01/01/2013 00:45      21
5 01/01/2013 01:00      27
6 01/01/2013 01:15      31

The expected output looks like this:

      Date  Time  Value_1  Value_2  Value_3
1 01/01/2013 00:00     84      38        23
2 01/01/2013 00:15     71      29        13
3 01/01/2013 00:30     73      27        11
4 01/01/2013 00:45     73      32        21   
5 01/01/2013 01:00     73      36        27
6 01/01/2013 01:15     80      40        31

Solution

  • Is there a need to call an anonymous function here? Can we just call merge directly in the Reduce function?

    z <- data.frame(id = c(1,2,3,4),a =c(1,2,3,4), b0 = c(4,3,2,1))
    x <- data.frame(id = c(1,2,3,4),a =c(1,2,3,4), b3 = c(6,3,2,1))
    y <- data.frame(id = c(1,2,3,4),a =c(1,2,3,4), z1 = c(4,3,2,1))
    
    l <- list(x,y,z)
    
    Reduce(merge, l)
    
    #output
     id a b3 z1 b0
      1 1  6  4  4
      2 2  3  3  3
      3 3  2  2  2
      4 4  1  1  1