Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>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))
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading