Home > Software engineering >  Expand one column but fix the rest two columns with expand.grid()
Expand one column but fix the rest two columns with expand.grid()

Time:11-26

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.

To clarify why this happens, see the merge manual:

If by or both by.x and by.y are of length 0 (a length zero vector or NULL), the result, r, is the Cartesian product of x and y, i.e., dim(r) = c(nrow(x)*nrow(y), ncol(x) ncol(y)).

  •  Tags:  
  • r
  • Related