首页 > 解决方案 > 从字符日期字段 R 中提取年份和月份

问题描述

我的大型数据集中有一列名为Date. 如何从中提取年份和月份?我想创建一个列Month,其中月份1-12year年份从我的数据集中的第一年到我的数据集中的最后一年。

谢谢。

> typeof(data$Date)
[1] "character

> head(data$Date)
[1] "2/06/2020 11:23"  "12/06/2020 7:56"  "12/06/2020 7:56"  "29/06/2020 16:54" "3/06/2020 15:09"  "25/06/2020 17:11"

标签: rdatedatetime

解决方案


dplyrlubridate-

library(dplyr)
library(lubridate)

data <- data %>%
  mutate(Date = dmy_hm(Date), 
         month = month(Date), 
         year = year(Date))

#                 Date month year
#1 2020-06-02 11:23:00     6 2020
#2 2020-06-12 07:56:00     6 2020
#3 2020-06-12 07:56:00     6 2020
#4 2020-06-29 16:54:00     6 2020
#5 2020-06-03 15:09:00     6 2020
#6 2020-06-25 17:11:00     6 2020

基数 R -

data$Date <- as.POSIXct(data$Date, tz = 'UTC', format = '%d/%m/%Y %H:%M')
data <- transform(data, Month = format(Date, '%m'), Year = format(Date, '%Y'))

数据

data <- structure(list(Date = c("2/06/2020 11:23", "12/06/2020 7:56", 
"12/06/2020 7:56", "29/06/2020 16:54", "3/06/2020 15:09", "25/06/2020 17:11"
)), class = "data.frame", row.names = c(NA, -6L))

推荐阅读