Search code examples
rdataframe

Use expand.grid on data.frame and vector


df <- data.frame(x=c("a","b","c"), y = c(100,200,300))
v <- 1:4

I'm trying to add the vector v to a dataframe df such that each row of df is combined with each element of v

x   y   v
a   100 1
a   100 2
a   100 3
a   100 4
b   200 1
b   200 2
b   200 3
b   200 4
c   300 1
c   300 2
c   300 3
c   300 4

How can I achieve this result?


Solution

  • You can use crossing from the tidyr package.

    tidyr::crossing(df, v)
    

    Or if you want to do it in base R, here is one possible solution:

    df2 <- df[rep(seq_len(nrow(df)), each = length(v), ]
    df2$v <- rep_len(v, nrow(df2))