2014-05-15 18 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"