【问题标题】:Formatting dates and creating dummy variables for dates格式化日期并为日期创建虚拟变量
【发布时间】:2021-05-13 07:51:41
【问题描述】:

来自一位经验不足的程序员的问题。我正在尝试创建虚拟变量来指示问题是否在 2008 年 9 月 15 日(金融危机)之后。我的数据集的日期格式如下:15-09-2008。由于变量被 R 识别为字符,我尝试通过运行以下代码将其转换为日期:

c$NewDate <- strptime(c$IssueDate, "&d-&m-&Y")

format(c$NewDate, "&Y/&m/&d")

但是,上面的代码已经导致变量 c$NewDate 只返回 NA,而数据帧 c 中根本没有 NA。我真的不明白它是从哪里来的。

正如我所说,我的主要目标是创建虚拟变量。我已经在 dd-mm-yy 格式中尝试了以下代码:c$GFC <- ifelse(c$IssueDate > as.Date("15-09-2008", origin = "10-01-1986"), 0, 1),但这不起作用。它表示 1986 年 1 月 10 日发行的 1 和 1986 年 24 月 1 日发行的 0。因此,这根本没有意义。如果有比这更快的方法来创建指示问题是否在 2008 年 9 月 15 日之后出现的虚拟对象,我也很想知道!

Image showing what's going wrong

Image showing what's going wrong

【问题讨论】:

标签: r special-characters date-formatting


【解决方案1】:

我强烈推荐tidyverselubridate 来处理这个问题。


library(tidyverse)
library(lubridate)

# generate the test data
temp <- data.frame(mytime = c("14-09-2008", "13-5-2021"))


temp <- 
  temp %>%
  
  # create a "tibble" object which can be operated by tidyverse package
  as_tibble() %>%
  
  # transform the format from a character into a date
  mutate(mytime = dmy(mytime)) %>%
  
  # generate indicators
  mutate(indicator = mytime <= dmy("15-09-2008") )

或者你只使用lubridate包:

> temp$mytime
[1] "14-09-2008" "13-5-2021" 
> date_format <- dmy(temp$mytime)
> date_format
[1] "2008-09-14" "2021-05-13"
> ifelse(date_format <= dmy("15-09-2008"), 1, 0)
[1] 1 0

【讨论】:

  • 首先,非常感谢!但是,在运行变异代码时,我收到以下错误..:no applicable method for 'mutate' applied to an object of class "character"
  • mutate 函数只能对 Tibble 对象进行操作。可以选择不使用这个功能,直接参考我刚刚添加的答案。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2019-11-22
  • 1970-01-01
  • 1970-01-01
  • 2021-05-16
  • 1970-01-01
  • 2021-01-19
  • 1970-01-01
相关资源
最近更新 更多