[R] count the # of appearances...

(Ted Harding) ted.harding at nessie.mcc.ac.uk
Thu Mar 1 16:11:23 CET 2007


On 01-Mar-07 bunny , lautloscrew.com wrote:
> Hi there,
> 
> is there a possibility to count the number of appearances of an  
> element in a vector ?
> i mean of any given element.. deliver all elements which are exactly  
> xtimes in this vector ?
> 
> thx in advance !!

If it is a specific element value which you designate beforehand,
then Ranjan Maitra's method

  sum(your vector == your chosen element)

will of course give you the number of times this occurs.

However, your query suggests this may not be what you want.

First, if you do not designate a specific element, then table()
can give you counts of repetitions of all the distinct elements.
For example:

## Generate the vector y with repetitions of elements of x:
> x<-round(runif(10),digits=3)
> y<-sample(x,25,replace=TRUE)

## Count the numbers of repetitions
> x<-round(runif(10),digits=3)
> y<-sample(x,25,replace=TRUE)
> table(y)
## y
## 0.122 0.372 0.431 0.486 0.523 0.858 0.886 0.948 
##    5     4     5     3     3     2     2     1 

Second: You ask for a method to "deliver all elements which are
exactly xtimes in this vector". So suppose "xtimes" is a given
number of times, and you want to know all elements which each
occur xtimes times in the vector y.

You could base a method for this on the ouput of table()
as above (look at "?table" for the background).

  counts <- as.data.frame(table(y))
  counts
##       y Freq
## 1 0.122    5
## 2 0.372    4
## 3 0.431    5
## 4 0.486    3
## 5 0.523    3
## 6 0.858    2
## 7 0.886    2
## 8 0.948    1

so, if your "xtimes" is say 3, then

  counts$y[counts$Freq==3]
## [1] 0.486 0.523
## Levels: 0.122 0.372 0.431 0.486 0.523 0.858 0.886 0.948

showing that elements "0.486" and "0.523" occurred 3 times each
in the vector y.

Hoping this helps,
Ted.

--------------------------------------------------------------------
E-Mail: (Ted Harding) <ted.harding at nessie.mcc.ac.uk>
Fax-to-email: +44 (0)870 094 0861
Date: 01-Mar-07                                       Time: 15:11:09
------------------------------ XFMail ------------------------------



More information about the R-help mailing list