Grant Grant - 1 year ago 101
R Question

R: Incorrect Dates After Using read.csv

This has me stumped. I have tried several solutions that I've found elsewhere on SO and other places to no avail. The closest one to my problem appears to be this question:

Convert factor to date object R without NA

I'm trying to read in a .csv that has date information. The column with the dates in it reads in as a factor. When I convert it to the "date" class, the dates get garbled. Below is a Dropbox link to a simple .csv file that should allow you to reproduce the problem:

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

Code:

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


All of the years get changed to 2020, when they should start with 2001 and end with 2009. How can I get the dates to display as dates without the values being changed incorrectly?

Answer Source

try this:

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

To read as 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

To import the file as xts-object:

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" 
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download