简体   繁体   中英

How to add missing rows of data as NA in tidyverse

I've tried using complete to pad my data with NAs but am coming up empty.

df <- data.frame(Quarter = c("Current Quarter", "Previous Year", "Current Quarter", "Previous Quarter", "Previous Year"),
           Name = c("Zach", "Zach", "Tom", "Tom", "Tom"),
           Score1 = c(1, 2, 1, 2, 1),
           Score2 = c(8, 9, 10, 11, 12))
df

Returns:

           Quarter Name Score1 Score2
1  Current Quarter Zach      1      8
2    Previous Year Zach      2      9
3  Current Quarter  Tom      1     10
4 Previous Quarter  Tom      2     11
5    Previous Year  Tom      1     12

I would love to use complete to get the df to look like this:

           Quarter Name Score1 Score2
1  Current Quarter Zach      1      8
2 Previous Quarter Zach     NA     NA
3    Previous Year Zach      2      9
4  Current Quarter  Tom      1     10
5 Previous Quarter  Tom      2     11
6    Previous Year  Tom      1     12

Using complete

library(tidyverse)
df %>% complete(Quarter, Name)

#  Quarter          Name  Score1 Score2
#  <fct>            <fct>  <dbl>  <dbl>
#1 Current Quarter  Tom        1     10
#2 Current Quarter  Zach       1      8
#3 Previous Quarter Tom        2     11
#4 Previous Quarter Zach      NA     NA
#5 Previous Year    Tom        1     12
#6 Previous Year    Zach       2      9

We can arrange it the way we want

df %>% 
  complete(Quarter, Name) %>%
  arrange(desc(Name))

#  Quarter          Name  Score1 Score2
#  <fct>            <fct>  <dbl>  <dbl>
#1 Current Quarter  Zach       1      8
#2 Previous Quarter Zach      NA     NA
#3 Previous Year    Zach       2      9
#4 Current Quarter  Tom        1     10
#5 Previous Quarter Tom        2     11
#6 Previous Year    Tom        1     12

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM