R:使用read.csv后的日期不正确

时间:2017-02-07 14:24:49

标签: r

这让我很难过。我尝试了几种我在SO和其他地方找到的解决方案无济于事。最接近我问题的似乎是这个问题:

Convert factor to date object R without NA

我试图阅读包含日期信息的.csv。其中包含日期的列作为因子读入。当我将它转换为" date"上课,日期变得乱码。下面是一个简单的.csv文件的Dropbox链接,可以让你重现这个问题:

https://www.dropbox.com/s/07xuuy6pmw3qctt/dates.csv?dl=0

代码:

dates <- read.csv("dates.csv")


dates
        Name      Date
1   Person 1  1/1/2000
2   Person 2  2/1/2001
3   Person 3  3/1/2002
4   Person 4  4/1/2003
5   Person 5  5/1/2004
6   Person 6  6/1/2005
7   Person 7  7/1/2006
8   Person 8  8/1/2007
9   Person 9  9/1/2008
10 Person 10 10/1/2009



dates$Date <- as.Date(dates$Date, "%m/%d/%y")
dates

dates
        Name       Date
1   Person 1 2020-01-01
2   Person 2 2020-02-01
3   Person 3 2020-03-01
4   Person 4 2020-04-01
5   Person 5 2020-05-01
6   Person 6 2020-06-01
7   Person 7 2020-07-01
8   Person 8 2020-08-01
9   Person 9 2020-09-01
10 Person 10 2020-10-01

所有这些年都改为2020年,当时它们应从2001年开始到2009年结束。如何才能将日期显示为日期而不会错误地更改数值?

1 个答案:

答案 0 :(得分:0)

试试这个:

dbName <- "https://dl.dropboxusercontent.com/s//07xuuy6pmw3qctt/dates.csv” #your file

读作data.frame

df <- read.csv(dbName,header=TRUE,stringsAsFactors=F)
df$Date <- as.Date(df$Date,format ='%m/%d/%Y' )
head(df)
        Name       Date
1   Person 1 2000-01-01
2   Person 2 2001-02-01
3   Person 3 2002-03-01
4   Person 4 2003-04-01
5   Person 5 2004-05-01
6   Person 6 2005-06-01

将文件导入为xts - 对象:

dbFile <- as.xts(read.zoo(dbName,sep=',',header=TRUE,index.column = 2,format='%m/%d/%Y',stringsAsFactors=F))
names(dbFile) <- "name"

head(dbFile)
           name       
2000-01-01 "Person 1" 
2001-02-01 "Person 2" 
2002-03-01 "Person 3" 
2003-04-01 "Person 4" 
2004-05-01 "Person 5" 
2005-06-01 "Person 6"