Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Counting the number of elements with the values of x in a vector

I have a vector of numbers:

numbers <- c(4,23,4,23,5,43,54,56,657,67,67,435,          453,435,324,34,456,56,567,65,34,435) 

How can I have R count the number of times a value x appears in the vector?

like image 556
RQuestions Avatar asked Dec 17 '09 17:12

RQuestions


People also ask

Which of the following functions is used to know the number of elements of a vector in R?

We can check the type of vector with the help of the typeof() function. The length is an important property of a vector. A vector length is basically the number of elements in the vector, and it is calculated with the help of the length() function.


2 Answers

You can just use table():

> a <- table(numbers) > a numbers   4   5  23  34  43  54  56  65  67 324 435 453 456 567 657    2   1   2   2   1   1   2   1   2   1   3   1   1   1   1  

Then you can subset it:

> a[names(a)==435] 435    3 

Or convert it into a data.frame if you're more comfortable working with that:

> as.data.frame(table(numbers))    numbers Freq 1        4    2 2        5    1 3       23    2 4       34    2 ... 
like image 71
Shane Avatar answered Sep 20 '22 09:09

Shane


The most direct way is sum(numbers == x).

numbers == x creates a logical vector which is TRUE at every location that x occurs, and when suming, the logical vector is coerced to numeric which converts TRUE to 1 and FALSE to 0.

However, note that for floating point numbers it's better to use something like: sum(abs(numbers - x) < 1e-6).

like image 27
hadley Avatar answered Sep 20 '22 09:09

hadley