繁体   English   中英

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

[英]How to add missing rows of data as NA in tidyverse

我试过使用 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

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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