在R中的1列中设置多个日期的格式
我有一个从Excel读入R的日期列,其格式如下:“6/12/2019 12:00:00 AM”和“43716” 我想将此列转换为数字格式MM/DD/YYYY。我该怎么做 谢谢 我推荐在R中的1列中设置多个日期的格式,r,date,format,R,Date,Format,我有一个从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(),字符串将作为日期对象读入。一种方法是分别处理这两种格式 #Co
read.csv(file.csv,colClasses="character") #or whatever read function you're using
这将确保字符串正确地从原始文件转换为R
然后我将使用lubridate包中的
mdy()
,字符串将作为日期对象读入。一种方法是分别处理这两种格式
#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$updated_date我强烈建议不要这样做。这将使所有列变为字符
向量,这将要求您手动将包含数字的任何列转换回数字
或整数
。可能重复(仅从该答案的日期调整日期/时间格式)。
df <- data.frame(x = 1:3, date_col = c("6/12/2019 12:00:00 AM", "43716",
"6/16/2019 1:00:00 PM"))