交叉加入R中的dplyr

时间:2016-02-15 10:10:56

标签: r dplyr

library(dplyr)
cust_time<-data.frame(cid=c("c1","c2","c3","c4","c5"),ts=c(2,7,11,13,17))
#I want to do a cross join on self, preferable in dplyr else base package is Ok
#But w/o renaming header names
#Currently I have to create a duplicate cust_time to do this.
cust_time.1<-rename(cust_time,cid1=cid,ts1=ts)
merge(cust_time,cust_time.1,by=NULL)

#Later I will want to do cross join within the grouped region
cust_time <-mutate(cust_time,ts.bucket=ts%/%10)
#If using duplicate tables, not sure, how to do the below
#group_by(cust_time,ts.bucket) %>%
#do cross join within this bucket

基本上,我想在桌面上进行交叉自联接,但由于我不能使用dplyr解决方案,所以我使用了基本包。但它需要我重命名所有列。但是,我后来希望能够在分组级别进行交叉连接,这就是我磕磕绊绊的地方 任何帮助表示赞赏。

3 个答案:

答案 0 :(得分:10)

你只需要一个虚拟列来加入:

cust_time$k <- 1
cust_time %>% 
  inner_join(cust_time, by='k') %>%
  select(-k)

或者,如果您不想修改原始数据框:

cust_time %>%
  mutate(k = 1) %>%
  replicate(2, ., simplify=FALSE) %>%
  Reduce(function(a, b) inner_join(a, b, by='k'), .) %>%
  select(-k)

答案 1 :(得分:7)

dplyr 1.0版开始,您可以通过指定by = character()进行交叉连接:

cust_time %>% full_join(cust_time, by = character())

答案 2 :(得分:5)

这是一个完全dplyr兼容的解决方案。它与attitude_stool的解决方案有许多相同的想法,但它的优点是只有一行。

require(magrittr)  # for the %<>% operator

# one line:
(cust_time %<>% mutate(foo = 1)) %>% 
        full_join(cust_time, by = 'foo') %>% 
        select(-foo)