Counting the number of elements with the values of x in a vector
You can just use table()
:
> a <- table(numbers)> anumbers 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 Freq1 4 22 5 13 23 24 34 2...
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 sum
ing, 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)
.