[R] how to ignore NA when using cumsum?
Ista Zahn
istazahn at gmail.com
Sat Nov 21 21:12:35 CET 2009
Hi Tracy,
What do you want the program to do with the missing values? If you
want to treat them as zeros, you could use
cum.na <- function(x) {
x[which(is.na(x))] <- 0
return(cumsum(x))
}
cumsums <- apply(proportion, 1, cum.na)
-Ista
On Sat, Nov 21, 2009 at 2:34 PM, Tracy Bowerman
<tracy.bowerman at aggiemail.usu.edu> wrote:
> I would like to cumulatively sum rows in a matrix, in which each row has 1
> NA value. The usual "na.rm=TRUE" does not seem to work with the command
> cumsum. Is there another way to ignore the NAs or do I need to figure out a
> different way to do this?
>
> Here's an example matrix of title "proportion":
>
> Ntrail Strail NFJD Baldy Onion Crane
> [1,] NA 0.2944937 0.1779969 0.1808015 0.2296511 0.11705683
> [2,] 0.2882713 NA 0.1795668 0.1823961 0.2316766 0.11808925
> [3,] 0.1716890 0.1769419 NA 0.3518116 0.2025204 0.09703714
> [4,] 0.1726311 0.1779128 0.3482548 NA 0.2036317 0.09756961
> [5,] 0.2252904 0.2321833 0.2059743 0.2092197 NA 0.12733223
> [6,] 0.2052614 0.2115415 0.1764081 0.1791877 0.2276013 NA
>
> I want cumulative sums for each row.
> Here's the code that works until it reaches an NA, then returns all
> subsequent values as NA. Adding na.rm=TRUE returns the error:
> Error in FUN(newX[, i], ...) : 2 arguments passed to 'cumsum' which
> requires 1
>
> cumsums <- apply(proportion, 1, cumsum)
>
> Thank you,
> Tracy
>
> [[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.
>
--
Ista Zahn
Graduate student
University of Rochester
Department of Clinical and Social Psychology
http://yourpsyche.org
More information about the R-help
mailing list