[R] Counter

0 views
Skip to first unread message

amor Gandhi

unread,
Jul 23, 2009, 6:44:16 AM7/23/09
to r-h...@stat.math.ethz.ch
Hi everyone,
 
Is there any counter function in R for the following purpose:
x <- matrix(c(1,1,0,2,1,0,0,2,0,1,2,1,2,1,0,1),nrow=4)
As I would like to know how many zeros, ones, and twos in each row of x?
 
Many thank in advance,
Amor
 
 



[[alternative HTML version deleted]]

Uwe Ligges

unread,
Jul 23, 2009, 6:56:10 AM7/23/09
to amor Gandhi, r-h...@stat.math.ethz.ch
apply(x, 1, table)

Uwe Ligges

> ------------------------------------------------------------------------
>
> ______________________________________________
> R-h...@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.

______________________________________________
R-h...@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.

Philipp Pagel

unread,
Jul 23, 2009, 6:59:30 AM7/23/09
to r-h...@r-project.org
On Thu, Jul 23, 2009 at 10:44:16AM +0000, amor Gandhi wrote:
> Hi everyone,
>
> Is there any counter function in R for the following purpose:
> x <- matrix(c(1,1,0,2,1,0,0,2,0,1,2,1,2,1,0,1),nrow=4)

> As I would like to know how many zeros, ones, and twos in each row of x?

Yes there is:

As you are interested int he counts by row you can use apply:

apply(x, 1, table)

cu
Philipp

--
Dr. Philipp Pagel
Lehrstuhl für Genomorientierte Bioinformatik
Technische Universität München
Wissenschaftszentrum Weihenstephan
85350 Freising, Germany
http://webclu.bio.wzw.tum.de/~pagel/

Jorge Ivan Velez

unread,
Jul 23, 2009, 9:36:51 AM7/23/09
to amor Gandhi, r-h...@stat.math.ethz.ch
Try also:
t( apply(x, 1, function(x) table( factor(x, levels = 0:2) ) ) )
# 0 1 2
# [1,] 1 2 1
# [2,] 1 3 0
# [3,] 3 0 1
# [4,] 0 2 2

See ?apply, ?table and ?factor for more details, examples and information.

HTH,

Jorge

> ______________________________________________
> R-h...@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.
>
>

[[alternative HTML version deleted]]

Reply all
Reply to author
Forward
0 new messages