【问题标题】:RStudio: Separate YYYY-MM-DD into Individual ColumnsRStudio:将 YYYY-MM-DD 分成单独的列
【发布时间】:2020-08-09 01:00:20
【问题描述】:

我对 R 相当陌生,我正在努力做一些可能超级简单的事情。

我下载了洛杉矶 2010 年至 2019 年的犯罪数据。有 2,114,010 行数据。现在,它在我的全球环境区域中被称为“df”。

我想操作一个名为“发生”的特定列 - 这是犯罪发生时间的日期参考。

现在设置为 YYYY-MM-DD(即 2010-02-20)。

我正在尝试将所有三个分成单独的列。我在这个论坛和 StackExchange 上搜索过、搜索过、搜索过、尝试过、尝试过,但就是无法正常工作。

我已尝试使用 Lubridate 并按照其他答案的说明进行操作,但它根本不会创建新列(年、月、日各一个)。

这是数据集中的一些代表...我没有包括所有不同的变量,因为它们不是问题。

如前所述,我试图将“发生”分成单独的年、月和日列。

> head(df, 10)[c('dr_no','occurred','time','area_name')]
       dr_no   occurred time area_name
1    1307355 2010-02-20 1350    Newton
2   11401303 2010-09-12   45   Pacific
3   70309629 2010-08-09 1515    Newton
4   90631215 2010-01-05  150 Hollywood
5  100100501 2010-01-02 2100   Central
6  100100506 2010-01-04 1650   Central
7  100100508 2010-01-07 2005   Central
8  100100509 2010-01-08 2100   Central
9  100100510 2010-01-09  230   Central
10 100100511 2010-01-06 2100   Central

【问题讨论】:

  • transform(df, year = format(occurred, "%Y"), month = format(occurred, "%m"), day = format(occurred, "%d"))
  • 我可以看到该进程在控制台中运行,因为它遍历所有数据。它正在添加年、月和日。但是,当我查看数据时,新列不存在。数据中的变量数量也保持不变 (28)。
  • 您需要将数据分配回一个对象。 df1 <- transform(df, year = format(....... 然后检查df1

标签: r date tidyverse lubridate


【解决方案1】:

我们可以通过tidyverselubridate 做到这一点

library(dplyr)
library(lubridate)
df <- df %>%         
       mutate(occurred = as.Date(occurred), 
              year = year(occurred), month = month(occurred), day = day(occurred))

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2016-06-21
    • 1970-01-01
    • 1970-01-01
    • 2023-03-08
    • 1970-01-01
    • 1970-01-01
    • 2014-04-30
    相关资源
    最近更新 更多