Problem with expand.grid with uneven vector lengths

Viewed 387

I have a dataframe and I want to create another data frame with all possible combinations of distinct values of each variable of the first data frame

dt = data.frame(A = c(10,2,3,8,2), B = c("K","F","F","K","K"))

dt1 <- dt %>%  distinct(A)
dt2 <- dt %>%  distinct(B)

expand.grid(A = dt1, B = dt2)

However this code returns the following error:

Warning message:
In format.data.frame(if (omit) x[seq_len(n0), , drop = FALSE] else x,  :
  corrupt data frame: columns will be truncated or padded with NAs
4 Answers

expand.grid crosses vectors, not data frames. If you only have one column in each data frame you can do this (tidyverse-free):

expand.grid(A=unique(dt$A), B=unique(dt$B))

If you have multiple columns I think this should work:

do.call(expand.grid,c(unique(dt["A"]),unique(dt["B"])))

although crossing() is probably a better idea if you're already in the tidyverse.

For this purpose, crossing can be used

library(tidyr)
crossing(dt1, dt2)

Also, if we concatenate (c) the datasets, it becomes a list and expand.grid works on it (in addition to the other answers extracting as a vector)

expand.grid(c(dt1, dt2))

dt1 and dt2 are dataframes in your code.

expand.grid(A = dt1$A, B = dt2$B)
   A B
1 10 K
2  2 K
3  3 K
4  8 K
5 10 F
6  2 F
7  3 F
8  8 F

Using data.table:

library(data.table)
setDT(dt)
dt[, CJ(A, B, unique = TRUE)]

#     A B
# 1:  2 F
# 2:  2 K
# 3:  3 F
# 4:  3 K
# 5:  8 F
# 6:  8 K
# 7: 10 F
# 8: 10 K
Related