Reputation: 1039
I have been trying to generate all combinations of an ordered pair of variables with a third variable, that is combine every pair (z1, z2) below with all z3.
theta <- seq(0, 2*pi, length = 5)
z1 <- cos(theta) ;z2 <- sin(theta)
z3 <- seq(-3, 3, length = 5)
I would normally use the expand.grid
function but here this is not appropriate as it will generate combinations of the three variables destroying the ordering. I was wondering, is there a function in R that can do this? All help is greatly appreciated, thank you.
Upvotes: 3
Views: 662
Reputation: 21621
Another alternative:
library(tidyr)
df <- data.frame(z1, z2, z3)
expand(df, nesting(z1, z2), z3)
Upvotes: 6
Reputation: 887118
We paste
the 'z1' and 'z2' and do the expand.grid
with 'z3'. From the output ('d1'), we split the 'Var1' i.e. the paste
d vectors into two columns.
d1 <- expand.grid(paste(z1,z2), z3)
transform(read.table(text=as.character(d1$Var1), header=FALSE), V3= d1$Var2)
Upvotes: 1