Read csv with dates and numbers

67,626

Solution 1

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]])

Solution 2

Perhaps you want to convert the character values to meaningful time values. In that case POSIXt time objects are a good choice.

Given your data file I'd do something like.

data <- read.table(file="...", sep = ";", as.is = TRUE)
data[,1] <- strptime(data[,1], "%Y-%m-%d")

Look up strptime in help for more details.

NOTE: If you're going to specify all the properties of the file just use read.table. The only purpose for all of the other read.xxx versions is to simplify the expression because the defaults are set. Here you used read.csv2 because it defaults to sep = ';'. Therefore, don't specify it again. Not having to specify that is the entire reason the command exists. Personally, I only use read.table because I can never remember the names/defaults of all the variants. In your case it's also the briefest call because it satisfies your header and dec defaults.

Solution 3

Add as.is=TRUE to the read.csv call.

Share:
67,626
Admin
Author by

Admin

Updated on December 30, 2020

Comments

  • Admin
    Admin over 3 years

    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.