使用 R 中的 data.table 包,我正在尝试使用合并方法创建两个 data.table 的笛卡尔积,就像在基础 R 中所做的那样。
在基地以下工作:
#assume this order data
orders <- data.frame(date = as.POSIXct(c('2012-08-28','2012-08-29','2012-09-01')),
first.name = as.character(c('John','George','Henry')),
last.name = as.character(c('Doe','Smith','Smith')),
qty = c(10,50,6))
#and these dates
dates <- data.frame(date = seq(from = as.POSIXct('2012-08-28'),
to = as.POSIXct('2012-09-07'), by = 'day'))
#get the unique customers
cust<-unique(orders[,c('first.name','last.name')])
#using merge from base R, get the cartesian product
merge(dates, cust, by = integer(0))
但是,相同的技术在使用 data.table 时不起作用,并且会引发此错误:
"Error in merge.data.table(dates.dt, cust.dt, by = integer(0)) : A non-empty vector of column names for `by` is required."
#data.table approach
library(data.table)
orders.dt <- data.table(orders)
dates.dt <- data.table(dates)
cust.dt <- unique(orders.dt[, list(first.name, last.name)])
#try to use merge (data.table) in the same manner as base
merge(dates.dt, cust.dt, by = integer(0))
Error in merge.data.table(dates.dt, cust.dt, by = integer(0)) : A non-empty vector of column names for `by` is required.
我希望结果反映所有日期的所有客户名称,就像在基础中一样,但是以以 data.table 为中心的方式进行。这可能吗?