How to join two data.frames in R with different variables and out of order?

2

I have two data.frames:

frame1 <- data.frame(dia=c("02/01/2017","03/01/2017","04/01/2017","05/01/2017"), y=c(2,2,1,2),w=c(4,4,2,2),z=c(25,16,24,30), k=c("sim","nao","sim","nao"))
frame2 <- data.frame(dia=c("05/01/2017","04/01/2017","03/01/2017","02/01/2017"), v1=c(1000,2000,3000,4000))

How do I join the second data.frame to the first? Do I need to leave the dates in the same order in both data.frames before joining them?

I tried to use the rbind function, but it did not work.

    
asked by anonymous 30.12.2017 / 03:32

1 answer

2

I imagine you want to merge the two data frames by columns. The function rbind() (r of row) uni by rows and the function cbind() (column c) by columns.

To use the cbind() function, you must first sort:

# order
frame2 <- frame2[order(match(frame2[,1],frame1[,1])),]
# unir data frames
cbind(frame1, frame2[2]) 

An easier way, without ordering, is to use the function merge() :

merge(frame1, frame2, by = "dia")

         dia y w  z   k   v1
1 02/01/2017 2 4 25 sim 4000
2 03/01/2017 2 4 16 nao 3000
3 04/01/2017 1 2 24 sim 2000
4 05/01/2017 2 2 30 nao 1000
    
30.12.2017 / 04:14