[R] Odp: ave and sd

Petr PIKAL petr.pikal at precheza.cz
Wed Nov 21 12:59:42 CET 2007


Hi

r-help-bounces at r-project.org napsal dne 21.11.2007 10:45:55:

> Dear list,
> 
> I'm still trying to calculate the sd for V2 for
> each group in V1 if V3 is '0':
> 
> > x
>     V1   V2 V3
> 1 A01 2.40  0
> 2 A01 3.40  1
> 3 A01 2.80  0
> 4 A02 3.20  0
> 5 A02 4.20  0
> 6 A03 2.98  1
> 7 A03 2.31  0
> 8 A04 4.20  0
> 
> # Work
> x$vmean <- ave(x$V2, x$V1, x$V3 == 0, FUN = mean)
> 
> # Work
> x$vsd2 <- ave(x$V2, x$V1, FUN = sd)
> 
> # Doesn't work
> x$vsd <- ave(x$V2, x$V1, x$V3 == 0, FUN = sd)



Problem comes from

 lapply(split(x$V2, interaction(x$V1, x$V3)), sd)
 
specifically from

> split(x$V2, interaction(x$V1, x$V3))

<snip>

$A02.1
numeric(0)

$A03.1
[1] 2.98

$A04.1
numeric(0)

> sd(1)
[1] NA
> sd(numeric(0))
Error in var(x, na.rm = na.rm) : 'x' is empty

I am not sure if what value shall sd, var or cov(x) return if x is empty. 
You probably have 2 options

rewrite sd to handle empty vectors
use another aggregate function together with some reordering, see eg.

 aggregate(x$V2, list(x$V1, x$V3 == 0), FUN = sd)


Regards
Petr

> 
> Thank you for any help!
> 
> Patrick
> 
> ______________________________________________
> 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