【问题标题】:How to split dates into year, month, day columns in rstudio? [duplicate]如何在rstudio中将日期拆分为年、月、日列? [复制]
【发布时间】:2020-04-15 02:18:03
【问题描述】:

我是 rstudio 的新手,所以这可能有一个非常简单的答案。我已经导入了一个超过 12000 行的表。我的一个专栏有“年-月-日”格式的不同日期,我想将这一列分成三个单独的年、月和日列,以便仅使用月份进行一些分析。我已经看到了这个问题的许多答案,但似乎没有一个对我有用。如何在不单独写出每个日期的情况下将这么多行转换为单独的列。

请注意,我尝试转换的列的日期格式为“Y%-m%-%d”。

我导入的表格是这样的:

        date_observed  latitude   Range
1       2018-03-04     9.934524   "6 to 15"
2       2019-06-20     9.942766   "6 to 15"
3       2018-07-07     14.007714  "6 to 15"
...
12408   2019-06-05     70.67493   "66 to 75"

我希望它看起来像这样:

        year  month  day  latitude   Range
1       2018  03     04   9.934524   "6 to 15"
2       2019  06     20   9.942766   "6 to 15"
3       2018  07     07   14.007714  "6 to 15"
...
12408   2019  06     05   70.67493   "66 to 75"

【问题讨论】:

  • 如果您分享一些有关您的数据的信息,会更容易提供帮助。您可以使用dput(head(df)) 共享几行数据,其中df 是您的数据框的名称。

标签: r


【解决方案1】:

有多种方法可以做到这一点。如果你的数据是这样的:

df <- data.frame(dates = c('2019-01-03', '2020-03-21'))

1) 在基础 R 中,我们可以使用format 将日期更改为日期类并分别提取日、月和年。

df$dates <- as.Date(df$dates)
transform(df, date = format(dates, "%d"), 
               month = format(dates, "%m"), year = format(dates, "%Y"))

#       dates date month year
#1 2019-01-03   03    01 2019
#2 2020-03-21   21    03 2020

2) 使用tidyr::separate 分割"-" 上的字符串

tidyr::separate(df, dates, c('year', 'month', 'day'), sep = "-",remove = FALSE)

3) 与 1) 相同,但使用 dplyr + lubridate

library(dplyr)
library(lubridate)

df %>%
  mutate(dates = as.Date(dates), 
         date = day(dates), month = month(dates), year = year(dates))

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-12-17
    • 2016-02-20
    • 2011-09-26
    • 2019-09-10
    • 2019-02-20
    • 1970-01-01
    • 2021-05-07
    • 1970-01-01
    相关资源
    最近更新 更多