Cross Join in dplyr in R

后端 未结 3 658
长发绾君心
长发绾君心 2021-01-04 01:55
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 ba         


        
相关标签:
3条回答
  • 2021-01-04 02:19

    Here's a solution that is completely dplyr-compatible. It shares many of the same ideas as attitude_stool's solution but has the advantage of only being one line.

    require(magrittr)  # for the %<>% operator
    
    # one line:
    (cust_time %<>% mutate(foo = 1)) %>% 
            full_join(cust_time, by = 'foo') %>% 
            select(-foo)
    
    0 讨论(0)
  • 2021-01-04 02:21

    As of dplyr version 1.0, you can do a cross join by specifying by = character():

    cust_time %>% full_join(cust_time, by = character())
    
    0 讨论(0)
  • 2021-01-04 02:32

    You just need a dummy column to join on:

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

    Or if you don't want to modify your original dataframe:

    cust_time %>%
      mutate(k = 1) %>%
      replicate(2, ., simplify=FALSE) %>%
      Reduce(function(a, b) inner_join(a, b, by='k'), .) %>%
      select(-k)
    
    0 讨论(0)
提交回复
热议问题