[R] Help with read.csv

Gabor Grothendieck ggrothendieck at gmail.com
Thu Mar 10 00:32:58 CET 2011


On Wed, Mar 9, 2011 at 5:32 PM, Giovanni Petris <gpetris at uark.edu> wrote:
>
> Hello,
>
> I have a file that looks like this:
>
> Date,Hour,DA_DMD,DMD,DA_RTP,RTP,,
> 1/1/2006,1,3393.9,3412,76.65,105.04,,
> 1/1/2006,2,3173.3,3202,69.20,67.67,,
> 1/1/2006,3,3040.0,3051,69.20,77.67,,
> 1/1/2006,4,2998.2,2979,67.32,69.10,,
> 1/1/2006,5,3005.8,2958,65.20,68.34,,
>
> where the ',' is the separator and I tried to read it into R, but...
>
>> y <- read.csv("Data/Data_tmp.csv", header = FALSE, skip = 1,
> +               colClasses = c("character", "int", rep("double", 4)),
> +               col.names = c("Date","Hour","DA_DMD","DMD","DA_RTP", "RTP"),
> +               flush = TRUE)
> Error in read.table(file = file, header = header, sep = sep, quote = quote,  :
>  more columns than column names
>
> count.fields() gives me 8 fields per line, so I tried other variations,
> like the following, with two fictitious extra fields, but...
>
>> y <- read.csv("Data/Data_tmp.csv", header = FALSE, skip = 1,
> +               colClasses = c("character", "int", rep("double", 6)),
> +               col.names = c("Date","Hour","DA_DMD","DMD","DA_RTP",
> +               "RTP", "XXX", "YYY"))
> Error in methods::as(data[[i]], colClasses[i]) :
>  no method or default for coercing "character" to "int"
>
> Could anybody please tell me what I am doing wrong and how I could read
> my data into R?
>

This works for me:

Lines <- "Date,Hour,DA_DMD,DMD,DA_RTP,RTP,,
1/1/2006,1,3393.9,3412,76.65,105.04,,
1/1/2006,2,3173.3,3202,69.20,67.67,,
1/1/2006,3,3040.0,3051,69.20,77.67,,
1/1/2006,4,2998.2,2979,67.32,69.10,,
1/1/2006,5,3005.8,2958,65.20,68.34,,"

read.csv(textConnection(Lines))

as does this:

read.table(textConnection(Lines),  skip = 1, sep = ",",
 col.names = c("Date","Hour","DA_DMD","DMD","DA_RTP", "RTP", "junk1", "junk2"),
 colClasses = c("character", "integer", rep("double", 6)))

-- 
Statistics & Software Consulting
GKX Group, GKX Associates Inc.
tel: 1-877-GKX-GROUP
email: ggrothendieck at gmail.com



More information about the R-help mailing list