cartesian product with dplyr R

前端 未结 6 559
清酒与你
清酒与你 2020-12-03 07:06

I\'m trying to find the dplyr function for cartesian product. I\'ve two simple data.frame with no common variable:

x <- data.frame(x=c(\"a\",\"b\",\"c\"))         


        
6条回答
  •  攒了一身酷
    2020-12-03 07:33

    When faced with this problem, I tend to do something like this:

    x <- data.frame(x=c("a","b","c"))
    y <- data.frame(y=c(1,2,3))
    x %>% mutate(temp=1) %>% 
    inner_join(y %>% mutate(temp=1),by="temp") %>%
    dplyr::select(-temp) 
    

    If x and y are multi-column data frames, but I want to do every combination of a row of x with a row of y, then this is neater than any expand.grid() option that I can come up with

提交回复
热议问题