简体   繁体   English

Rhr中的最新课程

[英]chr to date class in R

I have a data frame containing dates as characters , dd.mm.yyyy format. 我有一个包含日期为字符 ,数据帧dd.mm.yyyy格式。 want to convert those in date class, format yyyy-md . 要转换为日期类,格式为yyyy-md as.date() is not working returning error, do not know how to convert 'dates' to class “Date” as.date()无法正常返回错误, 不知道如何将“日期”转换为“日期”类

dates <- data.frame(cbind(c("5.1.2015", "6.1.2014", "17.2.2014", "28.10.2014")))
colnames(dates) <- c("dates")
as.Date(dates, format = "%Y-%m-%d")

new_format_dates <- cbind(gsub("[[:punct:]]", "", dates[1:nrow(dates),1]))
as.Date(new_format_dates, format = "%Y-%m-%d")

So I tried to replace the . 所以我试图更换. and reformat those dates under new_format_dates , returning result like [1] NA NA NA NA 并在new_format_dates下重新格式化这些日期,返回结果,例如[1] NA NA NA NA

Firstly, make your data.frames properly; 首先,使您的data.frames正确; don't use cbind in data.frame . 不要用cbinddata.frame Next, set the format argument of as.Date to the format you've got, including separators. 接下来,将as.Dateformat参数设置为您拥有的格式,包括分隔符。 If you don't know the symbol you need, check out ?strptime . 如果您不知道所需的符号,请查看?strptime

dates <- data.frame(dates = c("5.1.2015", "6.1.2014", "17.2.2014", "28.10.2014"))
dates$dates_new <- as.Date(dates$dates, format = "%d.%m.%Y")
dates
#        dates  dates_new
# 1   5.1.2015 2015-01-05
# 2   6.1.2014 2014-01-06
# 3  17.2.2014 2014-02-17
# 4 28.10.2014 2014-10-28
dates <- data.frame(cbind(c("5.1.2015", "6.1.2014", "17.2.2014", "28.10.2014")))
colnames(dates) <- c("dates")

dates$new_Dates <- gsub("[.]","-",dates$dates) 
dates$dates <- NULL
dates_new <- as.Date(dates$new_Dates, format = "%d-%m-%Y")

dates_new <- data.frame(dates_new)
print(dates_new)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM