tapply function with NA

classic Classic list List threaded Threaded
3 messages Options
Reply | Threaded
Open this post in threaded view
|

tapply function with NA

vincent.deluard
Hi R users,

I have a matrix "m" of the type:

m
       X4.20.2010 X4.19.2010   X4.16.2010
[1,]  0.008319468 0.00000000 -0.008250825
[2,]  0.005574136 0.01816118  0.073081608
[3,] -0.047830688 0.01612903 -0.030239833
[4,]           NA         NA           NA
[5,]  0.008746356 0.02848576 -0.025566107
[6,] -0.007990868 0.00000000 -0.026666667

I want to get the sum of each column. Normally I would do:

apply(m,2,sum)

but I get:

> apply(m,2,sum)
X4.20.2010 X4.19.2010 X4.16.2010
        NA         NA         NA

This is because of the presence of "NA" in m. How do you the equivalent of
> sum(m[1:6,1],na.rm=TRUE)
using apply?

Many thanks!
Reply | Threaded
Open this post in threaded view
|

Re: tapply function with NA

Richard M. Heiberger
It is exactly the same

tmp <- matrix(1:24,6,4)
tmp[4,] <- NA
tmp
apply(tmp, 2, sum, na.rm=TRUE)

        [[alternative HTML version deleted]]

______________________________________________
[hidden email] 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.
Reply | Threaded
Open this post in threaded view
|

Re: tapply function with NA

Gabor Grothendieck
In reply to this post by vincent.deluard
See ?colSums

On Mon, May 10, 2010 at 12:44 AM, vincent.deluard
<[hidden email]> wrote:

>
> Hi R users,
>
> I have a matrix "m" of the type:
>
> m
>       X4.20.2010 X4.19.2010   X4.16.2010
> [1,]  0.008319468 0.00000000 -0.008250825
> [2,]  0.005574136 0.01816118  0.073081608
> [3,] -0.047830688 0.01612903 -0.030239833
> [4,]           NA         NA           NA
> [5,]  0.008746356 0.02848576 -0.025566107
> [6,] -0.007990868 0.00000000 -0.026666667
>
> I want to get the sum of each column. Normally I would do:
>
> apply(m,2,sum)
>
> but I get:
>
>> apply(m,2,sum)
> X4.20.2010 X4.19.2010 X4.16.2010
>        NA         NA         NA
>
> This is because of the presence of "NA" in m. How do you the equivalent of
>> sum(m[1:6,1],na.rm=TRUE)
> using apply?
>
> Many thanks!
> --
> View this message in context: http://r.789695.n4.nabble.com/tapply-function-with-NA-tp2164930p2164930.html
> Sent from the R help mailing list archive at Nabble.com.
>
> ______________________________________________
> [hidden email] 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.
>

______________________________________________
[hidden email] 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.