Cross Join dplyr in R

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 

Basically, I want to make a cross-join to the table, but since I cannot use the dplyr solution, I used the base package. But this requires renaming all the columns. However, I later want to be able to cross-connect at a grouped level, and this is where I stumble.
Any help was appreciated.

+6
source share
2 answers

You just need a dummy column to connect:

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

Or, if you do not want to change the original data frame:

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

Here is a solution that completely matches t20>. It shares many of the same ideas as solution_stool, but has the advantage of only one line.

 require(magrittr) # for the %<>% operator # one line: (cust_time %<>% mutate(foo = 1)) %>% full_join(cust_time, by = 'foo') %>% select(-foo) 
+4
source

All Articles