r - 从字符日期字段 R 中提取年份和月份
问题描述
我的大型数据集中有一列名为Date
. 如何从中提取年份和月份?我想创建一个列Month
,其中月份1-12
和year
年份从我的数据集中的第一年到我的数据集中的最后一年。
谢谢。
> 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"
解决方案
dplyr
和lubridate
-
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))
推荐阅读
- kubernetes - 如何配置 Kubernetes Ingress 来重写 API 响应?
- html - 将 div 与其他 div 对齐
- java - 如何从哈希映射内部调用方法(与 :: 运算符有关?)
- linux - kubectl top 节点报告的内存利用率高于 Linux 系统命令
- javascript - 如何获取登录按钮以导航到仪表板?
- javascript - 获取由制表符分隔的行的每个单词
- python - 从字符串列表中,获取字典列表
- python - Manager isn't available; 'auth.User' has been swapped for 'diabetes.UserSignupModel'
- c++ - C++ 悬空引用在函数中创建的 Eigen::Matrix
- javascript - 我们可以在套接字 io 中用于 ping 超时的最大值是多少?