Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to combine a data frame and a vector

Tags:

r

df<-data.frame(w=c("r","q"), x=c("a","b"))
y=c(1,2)

How do I combine df and y into a new data frame that has all combinations of rows from df with elements from y? In this example, the output should be

data.frame(w=c("r","r","q","q"), x=c("a","a","b","b"),y=c(1,2,1,2))
  w x y
1 r a 1
2 r a 2
3 q b 1
4 q b 2
like image 274
Ben Avatar asked Sep 15 '25 07:09

Ben


1 Answers

data.frame(lapply(df, rep, each = length(y)), y = y)
like image 181
flodel Avatar answered Sep 17 '25 00:09

flodel