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.
我试图在两列上合并两个具有相同名称但不同对象类型和不同行数的数据帧。它们都是日期数据(即“2015-03-17 00:00:00”)并且格式相同。一个是double类型,另一个是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?
但它们都不起作用(它像笛卡尔产品一样)。我想知道我做错了什么以及如何正确地做到这一点?
1 个解决方案
#1
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:
我将使用Right外连接SQL框架,如下所示:
d1$Date <- as.POSIXct(d1$Date)
merge(d1,d2, all.y=TRUE, by="Date")
#1
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:
我将使用Right外连接SQL框架,如下所示:
d1$Date <- as.POSIXct(d1$Date)
merge(d1,d2, all.y=TRUE, by="Date")