【发布时间】:2020-03-23 15:20:55
【问题描述】:
我有一个日期列,我从 Excel 读取到 R 中,其格式为以下日期格式:例如“6/12/2019 12:00:00 AM”和“43716”。
我想将此列转换为数字格式 MM/DD/YYYY。我该怎么做?
谢谢!
【问题讨论】:
-
stackoverflow.com/q/58880848 的可能重复项(只是从该答案的仅限日期调整日期/时间格式)。
我有一个日期列,我从 Excel 读取到 R 中,其格式为以下日期格式:例如“6/12/2019 12:00:00 AM”和“43716”。
我想将此列转换为数字格式 MM/DD/YYYY。我该怎么做?
谢谢!
【问题讨论】:
我会推荐
read.csv(file.csv,colClasses="character") #or whatever read function you're using
这将确保字符串从原始文件正确转换为 R。
然后我将使用 lubridate 包中的mdy(),字符串将作为日期对象读入。
【讨论】:
character 向量,这将要求您手动将任何包含数字的列转换回 numeric 或 integer。
一种方法是分别处理这两种格式
#Convert date-time variables into date
df$updated_date <- as.Date(as.POSIXct(df$date_col, format = "%m/%d/%Y %I:%M:%S %p",
tz = "UTC"))
#Get indices of the one which are not converted from above
inds <- is.na(df$updated_date)
#Convert the remaining ones to date
df$updated_date[inds] <- as.Date(as.numeric(as.character(df$date_col[inds])),
origin = "1899-12-30")
#Comvert them to format required
df$updated_date <- format(df$updated_date, "%m/%d/%Y")
df
# x date_col updated_date
#1 1 6/12/2019 12:00:00 AM 06/12/2019
#2 2 43716 09/08/2019
#3 3 6/16/2019 1:00:00 PM 06/16/2019
数据
对此样本数据进行了测试:
df <- data.frame(x = 1:3, date_col = c("6/12/2019 12:00:00 AM", "43716",
"6/16/2019 1:00:00 PM"))
【讨论】: