[R] exporting tapply objects to csv-files

hadley wickham h.wickham at gmail.com
Tue Sep 9 17:29:46 CEST 2008


On Tue, Sep 9, 2008 at 3:48 AM, Kunzler, Andreas <a.kunzler at bzaek.de> wrote:
> Dear Everyone,
>
> I try to create a cvs-file with different results form the table function.
>
> Imagine a data-frame with two vectors a and b where b is of the class factor.
>
> I use the tapply function to count a for the different values of b.
>
> tapply(a,b,table)
>
> and I use the table function to have a look of the frequencies as a total
>
> table(a)
>
> I would like to put both results together in one txt or csv file that I can import to e.g. Excel.
>
> The export file should have a layout like
>
> 1,2,3,4,5,6,7 (possible values of a)
> 3,6,7,8,8,8,1 (Counts of a total)
> 1,2,3,4,5,3,0 (Counts of a where b==A)
> 2,4,4,4,3,5,1 (Counts of a where b==B)
>
> I tried to change the class of the table result to a matrix but I could not find a way to use the results of tapply. I use tapply because b has 15 different values.

An alternative would be to use reshape (http://had.co.nz/reshape):

mydf <- data.frame( a = sample(7, 100, rep = T), b =
sample(letters[1:15], 100, rep = T))

library(reshape)
mydf$value <- 1
cast(mydf, b ~ a, sum, margins="row.major", fill = 0)

Regards,

Hadley

-- 
http://had.co.nz/



More information about the R-help mailing list