Sophie
Sophie

Reputation: 97

merge two dataframe on columns with same name but different type in r?

I was trying to merge two dataframes on two columns with the same name but different object types and different number of rows. They are both date data (i.e. "2015-03-17 00:00:00") and in the same format. One is of type double and the other is of type character.

I tried

merge(d1,d2,all=T,by.x=as.character(d1$Date))
merge(d1,d2,all=T,by.y=as.numeric(d1$Date))
merge(d1,d2,all=T,by="Date")

but none of them work (it's doing like a cartesian product). I am wondering what I did wrong and how to do it in correctly?

Upvotes: 0

Views: 398

Answers (1)

GPP
GPP

Reputation: 46

I guess the easy way is to reconcile the types first. Given your data frames:

d1 <- data.frame(Date="2015-03-17",value=0)
d2 <- data.frame(Date=seq(as.POSIXct("2015-03-17"), as.POSIXct("2015-03-18"), by="days"))

I would use the Right outer join SQL framework as follows:

d1$Date <- as.POSIXct(d1$Date)
merge(d1,d2, all.y=TRUE, by="Date")

Upvotes: 2

Related Questions