2016-02-15 2 views
5
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 

असल में, मैं एक टेबल पर एक क्रॉस सेल्फ-जॉइन करना चाहता हूं लेकिन चूंकि मैं एक द्विध्रुवीय समाधान नहीं कर सकता, इसलिए मैंने बेस पैकेज का उपयोग किया। लेकिन मुझे सभी कॉलम का नाम बदलने की आवश्यकता है। हालांकि, मैं बाद में समूहबद्ध स्तर पर एक क्रॉस-जॉइन करने में सक्षम होना चाहता हूं और यह वह जगह है जहां मैं ठोकर खा रहा हूं।
किसी भी मदद की सराहना की।क्रॉस आर

+0

कोई '' ts.bucket' में – mtoto

+0

cust_time' आप 'की कोशिश कर सकते do.call (data.table :: सीजे, cust_time)' –

+0

@DavidArenburg, कि सिर्फ 'expand.grid (cust_time) है 'है ना? –

उत्तर

6

तुम बस पर शामिल होने के लिए एक डमी स्तंभ की जरूरत है:

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

या यदि आप अपने मूल dataframe संशोधित करने के लिए नहीं करना चाहती:

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

यहाँ एक समाधान पूरी तरह से dplyr संगत है कि । यह रवैया_स्टूल के समाधान के समान विचारों को साझा करता है लेकिन केवल एक पंक्ति होने का लाभ होता है।

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

# one line: 
(cust_time %<>% mutate(foo = 1)) %>% 
     full_join(cust_time, by = 'foo') %>% 
     select(-foo) 
संबंधित मुद्दे