[R] How to sum only a few elements in a line

Peter Alspach Peter.Alspach at plantandfood.co.nz
Wed Nov 25 21:45:54 CET 2009


Tena koe Marcio

Try something like (untested)

apply(yourMatrix, 1, function(x) sum(x[x!=9])) 

HTH ...

Peter Alspach

> -----Original Message-----
> From: r-help-bounces at r-project.org 
> [mailto:r-help-bounces at r-project.org] On Behalf Of Marcio Resende
> Sent: Thursday, 26 November 2009 9:27 a.m.
> To: r-help at r-project.org
> Subject: [R] How to sum only a few elements in a line
> 
> 
> Hello,
> 
> I have a matrix with the numbers 0,1 and 9 I would like to 
> write a function that could sum each line skiping everytime a 
> number 9 appears for example [0 1 0 1 1 9 1] the sum would be 4.
> However I cannot replace 9 by 0 otherwise after the sum is 
> done I wouldn´t be able to distiguish which ones were real 
> zeros and which ones were nines replaced by zero just to sum.
> Thank you very much
> 
> --
> View this message in context: 
> http://old.nabble.com/How-to-sum-only-a-few-elements-in-a-line
> -tp26519740p26519740.html
> Sent from the R help mailing list archive at Nabble.com.
> 
> ______________________________________________
> 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