在两个方向上转换 R 中的日期
Converting Dates in R in both Directions
我正在尝试使用 lubridate 将日期对象转换为日期 class。这些是“错误”格式的以下日期
wrong_format_date1 <- "01-25-1999"
wrong_format_date2 <- 25012005
wrong_format_date3 <- "2005-05-31"
但我希望它们采用这种格式:
"1999-01-25"
"2005-01-25"
"2005-05-31"
有人可以帮我解决这个问题吗?
试试这个。使用 lubridate
中的 parse_date_time()
,您可以在其中定义具有可能格式的向量,以便将字符串解析为日期。这里的代码:
library(lubridate)
#Data
wrong_format_date1 <- "01-25-1999"
wrong_format_date2 <- 25012005
wrong_format_date3 <- "2005-05-31"
#Dataframe
df <- data.frame(v1=c(wrong_format_date1,wrong_format_date2,wrong_format_date3),stringsAsFactors = F)
#Code
df$Date <- as.Date(parse_date_time(df$v1, c("mdY", "dmY","Ymd")))
输出:
v1 Date
1 01-25-1999 1999-01-25
2 25012005 2005-01-25
3 2005-05-31 2005-05-31
我正在尝试使用 lubridate 将日期对象转换为日期 class。这些是“错误”格式的以下日期
wrong_format_date1 <- "01-25-1999"
wrong_format_date2 <- 25012005
wrong_format_date3 <- "2005-05-31"
但我希望它们采用这种格式:
"1999-01-25"
"2005-01-25"
"2005-05-31"
有人可以帮我解决这个问题吗?
试试这个。使用 lubridate
中的 parse_date_time()
,您可以在其中定义具有可能格式的向量,以便将字符串解析为日期。这里的代码:
library(lubridate)
#Data
wrong_format_date1 <- "01-25-1999"
wrong_format_date2 <- 25012005
wrong_format_date3 <- "2005-05-31"
#Dataframe
df <- data.frame(v1=c(wrong_format_date1,wrong_format_date2,wrong_format_date3),stringsAsFactors = F)
#Code
df$Date <- as.Date(parse_date_time(df$v1, c("mdY", "dmY","Ymd")))
输出:
v1 Date
1 01-25-1999 1999-01-25
2 25012005 2005-01-25
3 2005-05-31 2005-05-31