Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
813 views
in Technique[技术] by (71.8m points)

r - Using tidyr::complete with group_by

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:

  1. Have I done anything wrong, or does complete() simply not work with group_by?
  2. If so, how could I do this instead (preferably without using a loop)?
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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)))

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...