[R] aggregate function

David Winsemius dwinsemius at comcast.net
Wed Dec 21 17:56:05 CET 2011


On Dec 21, 2011, at 11:31 AM, jim holtman wrote:

> Here is an example using 'data.table'"
>
>> x <- read.table(text = "param       case1
> + 1               a
> + 2               b
> + 2               c
> + 2               d
> + 3               e
> + 4               f", header = TRUE, as.is = TRUE)

And the aggregate version:

 > aggregate(x$case1, x["param"], FUN=paste, collapse=",")
   param     x
1     1     a
2     2 b,c,d
3     3     e
4     4     f

( Generally one uses the "[[" function for extraction, but using  "["  
returns a list which is what aggregate is designed to process as its  
second argument, whereas you would get an error with either of these:

aggregate(x$case1, x$param, FUN=paste, collapse=",")
aggregate(x$case1, x[["param"]], FUN=paste, collapse=",")
  )

>> require(data.table)
>> x <- data.table(x)
>> x[
> +     , list( case1 = paste(case1, collapse = ','))
> +     , by = param
> +  ]
>     param case1
> [1,]     1     a
> [2,]     2 b,c,d
> [3,]     3     e
> [4,]     4     f
>>
>
>
> On Wed, Dec 21, 2011 at 11:26 AM, Mary Kindall  
> <mary.kindall at gmail.com> wrote:
>> Hi
>> I have a data frame with values in following format.
>>
>>
>> param       case1
>> 1               a
>> 2               b
>> 2               c
>> 2               d
>> 3               e
>> 4               f
>>
>>
>> how to use aggregate so that it I only one row for each 'param'  
>> value.
>>
>> the output for the above input should be
>>
>> param     case1
>> 1      a
>> 2      b,c,d
>> 3      e
>> 4      f
>>
>> Thanks
>> M
>>
>>
>>
>> --
>> -------------
>> Mary Kindall
>> Yorktown Heights, NY
>> USA
>>
>>        [[alternative HTML version deleted]]
>>
>> ______________________________________________
>> 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.
>
>
>
> -- 
> Jim Holtman
> Data Munger Guru
>
> What is the problem that you are trying to solve?
> Tell me what you want to do, not how you want to do it.
>
> ______________________________________________
> 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.

David Winsemius, MD
West Hartford, CT



More information about the R-help mailing list