简体   繁体   English

dplyr::if_else - 检查条件并插入 NA 作为评估的一部分

[英]dplyr::if_else - check for condition and insert NA as part of the evaluation

I'm trying to solve a simple problem.我正在尝试解决一个简单的问题。 I check for a particular condition and if it is true I insert a date value or else insert NA (ie leave a blank cell).我检查一个特定的条件,如果它是真的,我插入一个date值或插入NA (即留下一个空白单元格)。

To get this to work, I'm using if_else but it is stubbornly refusing to work (and I have invested a couple of hours reading SO and help pages).为了if_else起作用,我正在使用if_else但它顽固地拒绝工作(我已经投入了几个小时阅读 SO 和帮助页面)。

This is what I have tried and failed:这是我尝试过但失败的方法:

library(tidyverse)
library(lubridate)

df <- data.frame(date   = dmy(c("01/01/2019", "02/01/2019", "03/01/2019")),
           status = c("Active", "Suspended", "Active"),
           stringsAsFactors = FALSE)

  df %>%  mutate(sus_date = if_else(status == "suspended", 1, 2))   # This works

  df %>% mutate(sus_date = if_else(status == "suspended", date, NA)) # Throws an Error
  Error: `false` must be a `Date` object, not a logical vector
  Call `rlang::last_error()` to see a backtrace.


  df %>% mutate(sus_date = if_else(status == "suspended", date, NA_real_)) # Throws an error
  Error in as.Date.numeric(value) : 'origin' must be supplied

This seem like a trivial problem and should not have taken so long to find an answer!这似乎是一个微不足道的问题,不应该花这么长时间才能找到答案!

Any ideas how to do this?任何想法如何做到这一点?

ps.附: I want to avoid using base::ifelse as it changes the date format我想避免使用base::ifelse因为它会更改日期格式

you can coerce the NA into date too, ie:您也可以强制NA生效,即:

df %>% mutate(sus_date = if_else(status == "Suspended", date, ymd(NA))) 
        date    status   sus_date
1 2019-01-01    Active       <NA>
2 2019-01-02 Suspended 2019-01-02
3 2019-01-03    Active       <NA>

if_else needs both true and false to be of same type, it returns an error because if_else需要truefalse为相同类型,它返回一个错误,因为

class(NA)
#[1] "logical"

whereas然而

class(df$date)
#[1] "Date"

Unfortunately, although we have NA_real , NA_character_ etc but there is no NA for dates so probably what you should do is不幸的是,虽然我们有NA_realNA_character_等,但日期没有NA所以你可能应该做的是

library(dplyr)
df %>% mutate(sus_date = as.Date(ifelse(status == "Suspended", date, NA)))

#        date    status   sus_date
#1 2019-01-01    Active       <NA>
#2 2019-01-02 Suspended 2019-01-02
#3 2019-01-03    Active       <NA>

Or as you are already using base R ifelse或者因为您已经在使用基础 R ifelse

transform(df, sus_date = as.Date(ifelse(status == "Suspended", date, NA)))

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

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