【问题标题】:How to use dates in functions in R?如何在 R 中的函数中使用日期?
【发布时间】:2019-12-07 23:10:22
【问题描述】:

我有一个数据框,其中有一列日期,我想创建一个新列来重新定义日期。

我正在使用一个函数来执行此操作,但我在定义我的日期时遇到了问题。

我的函数必须将我的数据分为 4 类:是、否、NA 或无效

may <- function(x) {
mayfunc <- function (x) { 
  # Classifies date as argument into categories {yes or no} or NA or invalid
  if (is.na(x)) {
    classification <- NA
  } else if (  x <  "2017-05-15" ) {
    classification <- "yes"
  } else if ( "2017-05-15" <= x ) {
    classification <- "no"
  } else {
    classification <- "invalid"
  }
  classification
}
sapply (x, mayfunc)
} 

我看不懂的结果

may("lalala")
may(2016-04-13)
may("2016-04-13")
may(2019-01-01)
may("2019-01-01")
may(300)
may(NA)
output: 
lalala 
 "no" --> why not invalid?
[1] "yes" --> correct
2016-04-13 
     "yes" --> correct
[1] "yes"  --> should be  "no"
2019-01-01 
     "no" --> correct
[1] "no" --> why not invalid?
[1] NA

我做错了什么?

【问题讨论】:

  • 您的日期在函数中被读取为字符串。
  • 尝试将as.Date 包裹在您的字符串日期周围,仅供参考,我认为在这里使用ifelse() 可能更合适
  • 没问题,如果下面的答案也对您有所帮助,请告诉我

标签: r function date select


【解决方案1】:

我认为我会改变一些事情。我不会嵌套函数,并且在函数调用中也有 sapply。我会创建一个函数,然后在全局环境中调用 sapply 中的函数。

这是我要使用的函数:

mayfun <- function(x){
  # stopifnot is optional - checks if it is a date
  stopifnot(inherits(x, "Date"))
  ifelse(is.na(x), NA,
         ifelse(x < as.Date("2017-05-15"), "yes",
          ifelse(as.Date("2017-05-15") <= x , "no", "invalid")))
}

然后你可以像这样在单个值上使用它:

#won't work
mayfun("lalala")
#works
mayfun(as.Date("2016-04-13"))
#works
mayfun(as.Date("2019-01-01"))
#won't work
mayfun(300)
#works
mayfun(as.Date(NA))

或者在这样的列上:

#silly example but it works
mtcars$newdate <- mayfun(as.Date(mtcars$mpg, origin = "1970-01-01"))

这样更优雅,但会覆盖日期变量:

#not tested
df[sapply(df, function(x){inherits(x,"Date")})] <- lapply(df[sapply(df, 
                                                  function(x){inherits(x,"Date")})], mayfun)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-11-24
    • 2011-11-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-11-26
    • 1970-01-01
    相关资源
    最近更新 更多