I want to use expand.grid (or something else) but fix first two columns and expand the third.
name <- c("bob", "mary")
sex <- c("male", "female")
num <- 1:2
result_desired <- data.frame(rep(name, each = 2),
rep(sex, each = 2),
rep(num), check.names = F)
result_desired
rep(name, each = 2) rep(sex, each = 2) rep(num)
1 bob male 1
2 bob male 2
3 mary female 1
4 mary female 2
CodePudding user response:
Let's define df
as
df <- data.frame(name,sex)
Then just use merge
like
merge(df, as.data.frame(num))
name sex num
1 bob male 1
2 mary female 1
3 bob male 2
4 mary female 2
will give your desired output.