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

Asked

Viewed 1,331 times

3

I have two date 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? It is necessary to leave dates in the same order on both data.frames before joining them together?

I tried to use the function rbind, but it didn’t work.

1 answer

4


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

To use the function cbind(), will have to order before:

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

An easier way, without having to sort, is by using 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

Browser other questions tagged

You are not signed in. Login or sign up in order to post.