首页 > 解决方案 > 将字符数据转换为日期——COVID 19 研究

问题描述

需要帮助将字符数据转换为日期:

时间/日期如下所示:4/10/20 17:36

我需要将列从字符转换为日期,以便按日期对列进行排序。我的数据框是o2outcomes,我的专栏是transfusion_date

我试过了:

  1. o2outcomes$transfusion_date <- as.Date(c("2007-06-22", "2004-02-13"))

  2. o2outcomes$transfusion_date <- as.Date(o2outcomes$transfusion_date , "%m/%d/%Y %H%M")

  3. o2outcomes <- data.frame(Date = c("10/9/2009 0:00:00", "10/15/2009 0:00:00")) as.Date(o2outcomes$transfusion_date, "%m/%d/%Y %H:%M")

为了按日期排列数据,我尝试过:

  1. o2outcomes$V8 <- lubridate::dmy(o2outcomes$transfusion_date) dplyr::arrange(o2outcomes$transfusion_date)

  2. o2outcomes[order(as.Date(o2outcomes$transfusion_date, format="%d/%m/%Y")),]

  3. test <- "2013-12-25T04:32:16.500-08:00

z <- as.POSIXct(test,format="%Y-%m-%dT%H:%M:%OS") op <- options(digits.secs = 3) z

'test <- "2013-12-25 04:32:16.5 CST" as.POSIXct(test)

4. o2outcomes$V8 <- lubridate::dmy(o2outcomes$transfusion_date) dplyr::arrange(o2outcomes$transfusion_date)

5. o2outcomes[order(as.Date(o2outcomes$transfusion_date, format="%d/%m/%Y")),]

这是一项对时间敏感的 COVID 研究(全国首个用于血浆疗法的研究!),尽管我以前从未使用过 R,但我的任务是创建这些数字。所以提前谢谢。

凯特

标签: rdate

解决方案


让我们弥补一些数据。你不需要这样做,因为你已经有了你的数据。我想你可能有更多的列,这不是问题。

o2outcomes <- data.frame(transfusion_date= c("4/10/20 17:36", "4/10/20 17:33", "4/11/20 17:36"),
                     other = letters[1:3])

这是它的样子:

  transfusion_date other
1    4/10/20 17:36     a
2    4/10/20 17:33     b
3    4/11/20 17:36     c

现在解析日期,然后按时间对数据集进行排序:

library(lubridate)

# parse date
o2outcomes$transfusion_date <- parse_date_time(o2outcomes$transfusion_date,
                                               orders = "%m/%d/%y %H%M")

# sort
o2outcomes <- o2outcomes[order(o2outcomes$transfusion_date),]

o2outcomes
     transfusion_date other
2 2020-04-10 17:33:00     b
1 2020-04-10 17:36:00     a
3 2020-04-11 17:36:00     c

推荐阅读