dplyr - 检查月份是否存在,如果没有,用 NA 添加它

lon*_*rew 2 r dplyr

关闭但不重复:在 tidyr/dplyr 中添加零计数行的正确习惯用法- 我试图根据 df 中的现有值进行填充,但也根据没有id. 相似,但本质不同。

对于每个id,我试图确保每个都有 3 个计费月。

理想情况下,对于每个id我都需要所有三个required months都出现在df_complete. 如果它不在数据中,我希望为值添加一行“未找到”。

此外,我想检查all_ids并添加在其中all_ids但没有行的IDdf

months <- as.data.frame(as.Date(c("2016/7/1","2016/9/1","2016/7/1", "2016/8/1","2016/9/1", "2016/8/1","2016/9/1"))) 
id <- as.data.frame(c("a","a","b","b","b","c","c"))
value <- as.data.frame(c(1,2,3,4,5,6,7))
df <- cbind(id,months,value)
colnames(df) <- c("id","billing months","value")
required_months <- as.data.frame(as.Date(c("2016/7/1", "2016/8/1","2016/9/1")))
colnames(required_months)<- "required months"
all_ids <- as.data.frame(c("a","b", "c", "d"))
Run Code Online (Sandbox Code Playgroud)

df 最终看起来像:

id  billing months  value
a   7/1/2016    1
a   9/1/2016    2
b   7/1/2016    3
b   8/1/2016    4
b   9/1/2016    5
c   8/1/2016    6
c   9/1/2016    7
Run Code Online (Sandbox Code Playgroud)

我在找什么(df_complete):

id  billing months  value
a   7/1/2016    1
a   8/1/2016    Not Found
a   9/1/2016    2
b   7/1/2016    3
b   8/1/2016    4
b   9/1/2016    5
c   7/1/2016    Not Found
c   8/1/2016    6
c   9/1/2016    7
d   7/1/2016    Not Found
d   8/1/2016    Not Found
d   9/1/2016    Not Found
Run Code Online (Sandbox Code Playgroud)

正在寻找dplyr解决方案,但其他软件包也可以。

aos*_*ith 5

这看起来像是 的工作tidyr::complete。由于原始数据集中缺少 id 变量和月份,因此您需要定义需要通过complete. 您可以定义您想要输入的缺失值的内容fill(尽管您的Not found值会将您的列从可能是一列数字的列更改为一列字符)。

suppressPackageStartupMessages( library(dplyr) )
library(tidyr)

df %>%
    complete(id = c("a","b", "c", "d"), 
             `billing months` = required_months$`required months`,
             fill = list(value = "Not found") )

#> Warning: Column `id` joining character vector and factor, coercing into
#> character vector

#> # A tibble: 12 x 3
#>    id    `billing months` value    
#>    <chr> <date>           <chr>    
#>  1 a     2016-07-01       1        
#>  2 a     2016-08-01       Not found
#>  3 a     2016-09-01       2        
#>  4 b     2016-07-01       3        
#>  5 b     2016-08-01       4        
#>  6 b     2016-09-01       5        
#>  7 c     2016-07-01       Not found
#>  8 c     2016-08-01       6        
#>  9 c     2016-09-01       7        
#> 10 d     2016-07-01       Not found
#> 11 d     2016-08-01       Not found
#> 12 d     2016-09-01       Not found
Run Code Online (Sandbox Code Playgroud)

reprex 包(v0.2.0)于2018年 3 月29 日创建。