2

I have a data frame dd and a vector vec. I want to multiply the dataframe as many times as is the length of the vector. Also, I want to add this vector element as a new column to the dataframe.

# Dummy data dd<- data.frame(id = c(1,2,3,4,5)) vec <- c("a", "b", "d") 

Desired output:

 id vec 1 1 a 2 2 a 3 3 a 4 4 a 5 5 a 6 1 b 7 2 b 8 3 b 9 4 b 10 5 b 11 1 d 12 2 d 13 3 d 14 4 d 15 5 d 

Originally, I would get the length(vec), use rep(vec, each = length(vec)) and then add this column to rbind(dd, dd,dd). But, if need to replicate dd twenty times, how to do this in a smarter way?

1
  • 1
    You seem to be looking for ?expand.grid Commented Apr 22, 2021 at 15:30

3 Answers 3

3

We can use crossing

library(tidyr) crossing(dd, vec) 
Sign up to request clarification or add additional context in comments.

Comments

3

Try:

vec <- data.frame(vec) merge(dd,vec) 

Output:

 id vec 1 1 a 2 2 a 3 3 a 4 4 a 5 5 a 6 1 b 7 2 b 8 3 b 9 4 b 10 5 b 11 1 d 12 2 d 13 3 d 14 4 d 15 5 d 

Comments

0

You can try rep like below

transform( dd, vec = rep(vec, each = length(id)) ) 

which gives

 id vec 1 1 a 2 2 a 3 3 a 4 4 a 5 5 a 6 1 b 7 2 b 8 3 b 9 4 b 10 5 b 11 1 d 12 2 d 13 3 d 14 4 d 15 5 d 

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.