2014-05-15 19 views
0

示例來自Phil Specter編寫的相當不可思議的書籍「David操縱R」,但出現錯誤。在R中,寫入表格時錯誤轉換爲Date類型

#write a gzipped csv file created from a data frame 

gfile = gzfile("mydata.gz") 
write.table("mydata, sep = ",", file = gfile") 

#Goal is to test a conversion from char to Date objects with function textConnection() 
sample = textConnection("2002-2-29 1 0 
         2002-4-29 1 5 
         2004-10-4 2 0") 

read.table(sample, colClasses = c("Date", NA, NA)) 

Error in charToDate(x) : 
    character string is not in a standard unambiguous format 

#next mydata = scan(unz("data.zip", "mydata.txt")) 
+0

這就是爲什麼我總是在日期爲字符讀,然後使用'format'字符串轉換爲'Date's。通過這種方式,我可以爲這些情況獲得一些不錯的「NA」,並且更容易調查爲什麼發生這些情況。 – Roland

+1

順便說一句,爲什麼有人想要操縱大衛?他是一個很好的人。 – Roland

回答

2

2月29日並沒有在2002年存在:

as.Date("2002-02-28") 
#[1] "2002-02-28" 
as.Date("2002-02-29") 
#Error in charToDate(x) : 
# character string is not in a standard unambiguous format 
as.Date("2004-02-29") 
#[1] "2004-02-29"