0

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?

talat
  • 68,970
  • 21
  • 126
  • 157
Sophie
  • 97
  • 1
  • 2
  • 7
  • Could you give a minimal reproducible example? See https://stackoverflow.com/questions/5963269/how-to-make-a-great-r-reproducible-example – talat May 06 '15 at 08:58
  • Say, `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 want to get a result like "Date: 2015-03-17 2015-03-18" and "value: 0 NA". @docendodiscimus – Sophie May 06 '15 at 09:14
  • You need to convert the columns to be merged to the same format beforehand. Note that any column in a data.frame can only hold data of 1 type/class. – talat May 06 '15 at 10:57

1 Answers1

2

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")
GPP
  • 46
  • 6