Generate combination of data frame and vector

后端 未结 3 552
一整个雨季
一整个雨季 2021-01-18 08:46

I know expand.grid is to create all combinations of given vectors. But is there a way to generate all combinations of a data frame and a vector by taking each r

3条回答
  •  天涯浪人
    2021-01-18 09:36

    This may not scale when your dataframe has more than two columns per row, but you can just use expand.grid on the first column and then merge the second column in.

    df <- data.frame(a = 1:3, b = 5:7)
    c <- 9:10
    combined <- expand.grid(a=df$a, c=c)
    combined <- merge(combined, df)
    > combined[order(combined$c), ]
      a  c b
    1 1  9 5
    3 2  9 6
    5 3  9 7
    2 1 10 5
    4 2 10 6
    6 3 10 7
    

提交回复
热议问题