R中的日期课程

时间:2016-04-06 04:34:35

标签: r

我的数据框包含日期为字符dd.mm.yyyy格式。想要转换日期类中的那些,格式为yyyy-m-das.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")

所以我尝试替换.并重新格式化new_format_dates下的日期,返回结果[1] NA NA NA NA

2 个答案:

答案 0 :(得分:3)

首先,正确地使您的data.frames;请勿在{{1​​}}中使用cbind。接下来,将data.frame format参数设置为您已获得的格式,包括分隔符。如果您不知道所需的符号,请查看as.Date

?strptime

答案 1 :(得分:1)

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)