Cartesian product data frame

后端 未结 7 2147
臣服心动
臣服心动 2020-11-29 18:47

I have three or more independent variables represented as R vectors, like so:

A <- c(1,2,3)
B <- factor(c(\'x\',\'y\'))
C <- c(0.1,0.5)
7条回答
  •  不知归路
    2020-11-29 19:29

    With library tidyr one can use tidyr::crossing (order will be as in OP):

    library(tidyr)
    crossing(A,B,C)
    # A tibble: 12 x 3
    #        A B         C
    #      
    #  1     1 x       0.1
    #  2     1 x       0.5
    #  3     1 y       0.1
    #  4     1 y       0.5
    #  5     2 x       0.1
    #  6     2 x       0.5
    #  7     2 y       0.1
    #  8     2 y       0.5
    #  9     3 x       0.1
    # 10     3 x       0.5
    # 11     3 y       0.1
    # 12     3 y       0.5 
    

    The next step would be to use tidyverse and especially the purrr::pmap* family:

    library(tidyverse)
    crossing(A,B,C) %>% mutate(D = pmap_chr(.,paste,sep="_"))
    # A tibble: 12 x 4
    #        A B         C D      
    #         
    #  1     1 x       0.1 1_1_0.1
    #  2     1 x       0.5 1_1_0.5
    #  3     1 y       0.1 1_2_0.1
    #  4     1 y       0.5 1_2_0.5
    #  5     2 x       0.1 2_1_0.1
    #  6     2 x       0.5 2_1_0.5
    #  7     2 y       0.1 2_2_0.1
    #  8     2 y       0.5 2_2_0.5
    #  9     3 x       0.1 3_1_0.1
    # 10     3 x       0.5 3_1_0.5
    # 11     3 y       0.1 3_2_0.1
    # 12     3 y       0.5 3_2_0.5
    

提交回复
热议问题