如何在tidyverse中将丢失的数据行添加为NA

时间:2018-10-12 01:44:45

标签: r tidyverse tidyr complete

我曾尝试使用complete将数据填充到NA中,但是却空了。

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

返回:

           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

我希望使用complete来使df看起来像这样:

           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

1 个答案:

答案 0 :(得分:2)

使用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

我们可以按照自己的方式arrange

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