Reputation: 180
I would like to expand a dataframe based on all pairwise combinations of one variable while keeping the associate value of a second variable. For example:
V1 <- letters[1:2]
V2 <- 1:2
df <- data.frame(V1, V2)
I would like to return:
Var1 Var2 Var3 Var4
a a 1 1
b a 2 1
a b 1 2
b b 2 2
I can use expand.grid(df$V1, df$V1)
to get all of the pairs, but I'm not sure how to include the second variable without having its values expanded also.
Upvotes: 1
Views: 206
Reputation: 886938
If we need to expand each column separately, then we can do this with Map
where the arguments are two 'df' objects
do.call(cbind, Map(expand.grid, df, df))
Upvotes: 1