tags:

views:

475

answers:

5

This is a simple problem, but for the life of me I cannot find the answer.

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)

I want to R to count the number of times a value "x" appears in the vector.

Any help?

+2  A: 

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
...
Shane
Don't forget about potential floating point issues, especially with table, which coerces numbers to strings.
hadley
That's a great point. These are all integers, so it isn't a real issue in this example, right?
Shane
not exactly. The elements of the table are of class integer class(table(numbers)[1]), but 435 is a floating point number. To make it an integer you can use 435L.
Ian Fellows
+1  A: 

here's one fast and dirty way:

x <- 23
length(subset(numbers, numbers==x))
JD Long
+1  A: 

I would probably do something like this

length(which(numbers==x))

But really, a better way is

table(numbers)
Jesse
`table(numbers)` is going to do a lot more work than the easiest solution, `sum(numbers==x)`, because it's going to figure out the counts of all the other numbers in the list too.
Ken Williams
+6  A: 

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).

hadley
good point about the floating point issue. That bites my butt more than I generally like to admit.
JD Long
A: 

table(number) works great

Magus