[R] Adding rows based on column value

Ben Bolker bbolker at gmail.com
Thu Jul 14 19:54:36 CEST 2011


On 07/14/2011 01:46 PM, Bansal, Vikas wrote:
> I have tried that also.But it is showing this error-
> 
>  aggregate(file[,3:6], by = list(file[,2]), FUN = sum)
> 
> Error in FUN(X[[1L]], ...) : invalid 'type' (character) of argument
> 
> 

 Farther down in your previous e-mail you state that you read the file
in using

file=read.table("file.txt",fill=T,colClasses = "character",header=T)

   the 'colClasses' argument is telling R to read in the data as type
"character", which of course it is having trouble summing (as the error
message suggests: R's error messages are often cryptic, but in this case
it seems to be telling you exactly what's wrong).  (You probably
put it in there so that R wouldn't mess up your second column, but it
was overkill. It converted *all* the columns to character.)

   Try changing your read statement to:

file=read.table("file.txt",fill=TRUE,
   colClasses = rep(c("character","numeric"),c(2,4)),header=TRUE)

(changing T to TRUE is safer; the different colClasses is the important
part.  fill=TRUE is probably unnecessary.)
  If you're unsure what this is doing, please do your best to read
?read.table and ?rep, and try out examples, before responding with
further queries ...

   Ben Bolker


> 
> Thanking you,
> Warm Regards
> Vikas Bansal
> Msc Bioinformatics
> Kings College London
> ________________________________________
> From: r-help-bounces at r-project.org [r-help-bounces at r-project.org] On Behalf Of Ben Bolker [bbolker at gmail.com]
> Sent: Thursday, July 14, 2011 6:24 PM
> To: r-help at stat.math.ethz.ch
> Subject: Re: [R] Adding rows based on column value
> 
> Bansal, Vikas <vikas.bansal <at> kcl.ac.uk> writes:
> 
>> I am using this-
>>
>> aggregate(x = file[,3:6], by = list(file[,2]), FUN = "sum")
>>
> 
>   Better, although still not reproducible (please *do* read the posting
> guide -- it is listed at the bottom of every R list post and is the
> *first* google hit for "posting guide" (!); search for
> "Examples").  What about removing the quotation marks around "sum"?
> 
>   aggregate(x = file[,3:6], by = list(file[,2]), FUN = sum)
> 
> 
>> but I think this is not a right way.
>> Because we cannot use "sum" to add.That is
>>  why I was asking for help.
> 
> ______________________________________________
> R-help at r-project.org mailing list
> https://stat.ethz.ch/mailman/listinfo/r-help
> PLEASE do read the posting guide http://www.R-project.org/posting-guide.html
> and provide commented, minimal, self-contained, reproducible code.



More information about the R-help mailing list