Read csv with dates and numbers

keanu picture keanu · Aug 24, 2010 · Viewed 65.1k times · Source

I have a problem when I import a csv file with R:

example lines to import:

2010-07-27;91
2010-07-26;93
2010-07-23;88

I use the statement:

data <- read.csv2(file="...", sep=";", dec=".", header=FALSE)

when I try to aggregate this data with other ones originated by statistical analysis using cbind, the date is showed as an integer number because it was imported as factor.

If I try to show it as a string using as.character, the numerical data are transformed into characters too so they are unusable for statistical procedures.

Answer

Marek picture Marek · Aug 24, 2010

Use colClasses argument:

data <- read.csv2(file="...", sep=";", dec=".", header=FALSE,
     colClasses=c("Date",NA))

NA means "proceed as default"

After import you could convert factor to Date by

data[[1]] <- as.Date(data[[1]])