将R数据框中的多列转换为日期格式 [英] Converting multiple columns in an R dataframe to Date Format

查看:663
本文介绍了将R数据框中的多列转换为日期格式的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个很大的数据文件,其中所有日期都已作为字符加载。我想将所有日期列更改为日期格式。大多数日期使用%y%m%d格式,某些日期使用%Y%m%d格式。有25列日期,因此单独更改每一列都是无效的。

I have a large datafile where all the dates have been loaded as charaters. I would like to change all the Dates columns to date format. Most of the dates have "%y%m%d" format, some have "%Y%m%d" format. There are 25 columns of dates, so changing each one individually is inefficient.

我可以做到

df$DATE1 <- as.Date(df$DATE1, format ="%y%m%d")
df$DATE2 <- as.Date(df$DATE2, format ="%y%m%d")

等,但是编码很差。

我尝试过以下代码,但无法正常工作。假定所有日期的格式均为%y%m%d。使用grep( DATE,names(df))将获取所有Dates列

I tried the following code, but is is not working. This assumes all of the dates are of the format "%y%m%d". Using grep("DATE", names(df)) will get all the Dates columns

df[ , grep("DATE", names(df))] <- as.Date(df[ , grep("DATE", names(df))], "%y%m%d")


推荐答案

尝试:

df[, cols <- grep("^DATE", names(df))] <- lapply(df[, cols <- grep("^DATE", names(df))], as.Date, format = "%y%m%d")

示例:

df <- data.frame(DATE1 = c('910812', '900928'), DATE2 = c('890813', '890910'))
# Apply the above and you get:
# > df
#        DATE1      DATE2
# 1 1991-08-12 1989-08-13
# 2 1990-09-28 1989-09-10
# > class(df[, 1])
# [1] "Date"

这篇关于将R数据框中的多列转换为日期格式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆