【问题标题】:Problem with ifelse() or dplyr::if_else() for dates日期的 ifelse() 或 dplyr::if_else() 问题
【发布时间】:2021-05-25 02:56:47
【问题描述】:

我想在矢量mydates 中转换实际日期中的 NA (Sys.Date()),如果值是日期,则不要更改任何内容,但我没有成功使用 ifelse 或 @ 987654324@ 的dplyr 包。在我的例子中:

# Package
library(dplyr)

# My vector
mydates<-c(NA,NA,NA,"2019-03-14","2020-05-01",NA,NA)

# Using ifelse
mydatescorr1<-ifelse(is.na(mydates)==TRUE,Sys.Date(),mydates)
mydatescorr1

[1] "18771"      "18771"      "18771"      "2019-03-14" "2020-05-01" "18771"      "18771" 

#Using if_else
mydatescorr2<-if_else(is.na(mydates)==TRUE,Sys.Date(),mydates)
mydatescorr2 

Erro: `false` must be a `Date` object, not a character vector.

请帮忙解决一下?

【问题讨论】:

    标签: r date dplyr


    【解决方案1】:

    mydates 是一个字符向量 (class(mydates)),因此当您从 else 部分返回 mydates 时,您将返回字符对象而不是日期。你可以使用 -

    dplyr::if_else(is.na(mydates), Sys.Date(), as.Date(mydates))
    

    或者没有if_else -

    mydates <- as.Date(mydates)
    mydates[is.na(mydates)] <- Sys.Date()
    

    【讨论】:

      【解决方案2】:

      怎么样

      tidyr::replace_na(as.Date(mydates), Sys.Date())
      

      ? (您仍然必须先将 mydates 转换为 Date 类型。)如果您愿意,可以通过管道传递:

      mydates %>% as.Date() %>% replace_na(Sys.Date())
      

      【讨论】:

        猜你喜欢
        • 2018-11-11
        • 1970-01-01
        • 2020-12-07
        • 1970-01-01
        • 2021-10-22
        • 2019-12-11
        • 1970-01-01
        • 2019-10-15
        • 2019-09-24
        相关资源
        最近更新 更多