Does anyone know if tidyr::complete() supports grouping via group_by()?
To be precise: I have some data frame that looks like this
df <- data.frame(
"ID" = rep(1:2, each = 2),
"Col1" = c("A", NA, "AA", NA),
"Col2" = c("B", "C", "BB", "CC"))
Now i'd like to use complete() and group_by() to compute all possible combinations per group!
df %>%
group_by(ID) %>%
complete(Col1, Col2)
Error in .Call("dplyr_left_join_impl", PACKAGE = "dplyr", x, y, by_x, :
negative length vectors are not allowed
This causes an error. However, using complete() without grouping works but thats not what i want.
df %>%
complete(Col1, Col2)
Questions:
complete() simply not work with group_by?You could do it using complete and group_by, but you have to use a do statement:
df %>%
group_by(ID) %>%
do(complete(., Col1, Col2, fill = list(ID = .$ID)))
We could do this using data.table. Convert the 'data.frame' to 'data.table' (setDT(df)), and Cross Join (CJ) the unique elements of 'Col1' and 'Col2', grouped by 'ID'.
library(data.table)#v1.9.6+
setDT(df)[,CJ(Col1, Col2, unique=TRUE), by = ID]
# ID V1 V2
#1: 1 NA B
#2: 1 NA C
#3: 1 A B
#4: 1 A C
#5: 2 NA BB
#6: 2 NA CC
#7: 2 AA BB
#8: 2 AA CC
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With