【发布时间】:2021-09-03 21:46:52
【问题描述】:
我有一个通常如下所示的数据框:
structure(list(date = structure(18780, class = "Date"), bar = 1L,
Sessions = 2990L, `bla` = 20L), row.names = c(NA,
-1L), class = c("tbl_df", "tbl", "data.frame"))
看起来像:
# A tibble: 1 x 4
date bar Sessions bla
<date> <int> <int> <int>
1 2021-06-02 1 2990 20
有了这个我变异了:
mydf %>% mutate(foo = bar + bla)
# A tibble: 1 x 5
date bar Sessions bla foo
<date> <int> <int> <int> <int>
1 2021-06-02 1 2990 20 21
但是,这是在带有用户过滤器的闪亮应用的上下文中。有时,用户输入后生成的数据框有一个没有 bar 或 bla 字段的数据框。因此,当我在 mutate 期间添加它们时,我得到了
Error: Problem with `mutate()` input `foo`.
x object 'bar' not found
ℹ Input `foo` is ``bar` + `bla``
在 bar 或 bla 不存在的情况下,我仍然希望我的 mutate 中剩余的总和。否则只需创建新功能 foo 但将其值设为 0。在 R 英语中类似于:
mydf %>% mutate(foo = if(bar exists then bar else 0) + if(bla exists then bla else 0))
有没有一种“不错”或优雅的方式来做到这一点?也许是 tidyverse 方法?
【问题讨论】: