R: 'Multiply' dataframe columns of strings

后端 未结 2 1466
礼貌的吻别
礼貌的吻别 2021-01-23 01:44

Not sure what this operation is called, and Google did not help.

Say I have two simple dataframes like this:

df1 <- data.frame(factor1 = c(\"a\", \"b         


        
相关标签:
2条回答
  • 2021-01-23 02:11

    Here is another option with expand.grid

    Map(expand.grid, factor1 = df1, factor2 = df2)$factor
    #    factor1 factor2
    #1       a       x
    #2       b       x
    #3       c       x
    #4       a       y
    #5       b       y
    #6       c       y
    #7       a       z
    #8       b       z
    #9       c       z
    
    0 讨论(0)
  • 2021-01-23 02:16

    It's a cartesian product of the two data frames, when there's no common names, you can use merge:

    merge(df1, df2)   
    
    #  factor1 factor2
    #1       a       x
    #2       b       x
    #3       c       x
    #4       a       y
    #5       b       y
    #6       c       y
    #7       a       z
    #8       b       z
    #9       c       z
    

    Or more explicitly:

    merge(df1, df2, by=c())
    

    According to ?merge, when there are no columns to join by, it returns a cartesian product of the two data frames:

    If by or both by.x and by.y are of length 0 (a length zero vector or NULL), the result, r, is the Cartesian product of x and y, i.e., dim(r) = c(nrow(x)*nrow(y), ncol(x) + ncol(y)).

    0 讨论(0)
提交回复
热议问题