在R中使用as.Date转换为日期并获得“NA”系列

时间:2014-01-16 14:08:17

标签: r date formatting import-from-csv

使用以下代码尝试将我的日期列设置为正确的格式,但它只是将所有日期返回为“NA”。

setwd("C:\\Users\\user\\Documents\\Files\\a")
data <- read.csv("file1.csv")

data$Date <- as.Date(data$Date, format = "d%/m%/Y%")

编辑:日期值如下:11/09/2009

2 个答案:

答案 0 :(得分:3)

来自?as.Date文档:

If the date string does not specify the date completely, the returned answer may be system-specific. The most common behaviour is to assume that a missing year, month or day is the current one. If it specifies a date incorrectly, reliable implementations will give an error and the date is reported as ‘NA’. Unfortunately some common implementations (such as ‘glibc’) are unreliable and guess at the intended meaning.

data$Date <- as.Date(data$Date, format = "%d/%m/%Y")

答案 1 :(得分:0)

您可以尝试使用包lubridate转换日期

library(lubridate)
date <- parse_date_time(x = date,
                orders = c("d m y", "d B Y", "mdy"),
                locale = "eng")

您可以指定日期的格式:

character_date <- as.character(as.Date(date, "%m/%d/%Y"), format = "%m/%d/%Y")