2014-01-16 42 views
1

使用以下代碼嘗試將我的日期列轉換爲正確格式,但它只是將所有日期返回爲「NA」。在R中使用as.Date轉換爲日期並獲取一系列「NA」s

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

+1

你能告訴我們的「日期」列的值。可能你在這裏指定的格式不匹配 – RUser

+3

嘗試'format =「%d /%m /%Y」'。 – Roland

回答

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") 
+0

選擇解決方案上的tic標記 - 使其成爲anwser,如果這有助於您 – RUser

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")