[R] aggregate without removing empty subset

Henrique Dallazuanna wwwhsd at gmail.com
Tue Mar 16 17:52:37 CET 2010


If the factor have only level:

apply(m1, 2, tapply, addNA(part2), mean)[-2,,drop = FALSE]


On Tue, Mar 16, 2010 at 12:43 PM, Christophe Genolini
<cgenolin at u-paris10.fr> wrote:
> As I told you in private, thanks, it works perfectly.
>
> More precisely, I am working with 3D array. Your code works well (both on
> matrix or on array).
> But when part is a factor with only one value, the result has not a correct
> dimension (vector if m is a matrix, a matrix if m is an array).
> Any way to fix that ?
>
> m1 <- matrix(1:12,4)
> m2 <- array(1:24,dim=c(4,3,2))
> part1 <- factor(c("A","B","A","B"),levels=c("A","B","C"))
> part2 <- factor(c("A","A","A","A"),levels=c("A"))
>
> apply(m1, 2, tapply, part1, mean) ##Perfect (dim=c(3,3))
> apply(m1, 2, tapply, part2, mean) ## dim=NULL...
>
> apply(m2, c(2,3), tapply, part1, mean) ## Perfect (dim=c(3,3,2))
> apply(m2, c(2,3), tapply, part2, mean) ## dim=c(3,2)
>
>
> Christophe
>
> Try this:
>
> apply(m, 2, tapply, part, mean)
>
> On Mon, Mar 15, 2010 at 2:10 PM, Christophe Genolini
> <cgenolin at u-paris10.fr> wrote:
>
>
> Hi the list,
>
> As it is say in its doc, the aggregate function remove empty subsets. Is it
> possible to NOT remove empty subset ?
> --- 8< -------
> m <- matrix(1:12,4)
> part <- factor(c("A","B","A","B"),levels=c("A","B","C"))
> aggregate(m,list(part),mean)
>
> ### I get:
> #   Group.1 V1 V2 V3
> # 1       A  2  6 10
> # 2       B  3  7 11
> #
> ### I would like:
> #   Group.1 V1 V2 V3
> # 1       A  2  6 10
> # 2       B  3  7 11
> # 3       C NA NA NA
> --- 8< ------
>
>
> Thanks
> Christophe
>
> ______________________________________________
> 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.
>
>
>
>
>



-- 
Henrique Dallazuanna
Curitiba-Paraná-Brasil
25° 25' 40" S 49° 16' 22" O



More information about the R-help mailing list