-2

I am searching for a function f counting for the number of occurences of certain values in a vector.

As example the inputs are:

value = c(1,3)
vec   = c(1,1,3,1,3,4,4,5,5,3,1)

And the output looks like:

1 3 
4 3 

For another input:

value = c(1,77,3,99)
vec   = c(1,1,3,1,3,4,4,5,5,3,1)

Output is:

1 77  3 99 
4  0  3  0 

So that it works also with characters, dates, etc, every type a vector can handle.

This function can do the job:

countOcurrences = function(values, vec)
{
    setNames(sapply(values, function(u) sum(vec==u)), values)
}

But I wonder if there are some functions existing in some unknown packages doing the job?

Colonel Beauvel
  • 30,423
  • 11
  • 47
  • 87
  • possible duplicate of [Counting the Number of Elements With The Values of x in a Vector?](http://stackoverflow.com/questions/1923273/counting-the-number-of-elements-with-the-values-of-x-in-a-vector) – Karolis Koncevičius Jan 11 '15 at 18:28
  • The question may be similar but the main point is to turn around table defaults when counting zeros when some values are not in the vector..@akrun you can post it as an answer :) – Colonel Beauvel Jan 11 '15 at 18:42
  • ok, the only transformation was to shift the input into the correct facotr ...thanks! – Colonel Beauvel Jan 11 '15 at 18:45

1 Answers1

3

Update

As indicated by @akrun in the comments, factor may be what you're actually looking for:

value = c(1,3)
vec   = c(1,1,3,1,3,4,4,5,5,3,1)
table(factor(vec, value))
# 
# 1 3 
# 4 3 

value = c(1,77,3,99)
vec   = c(1,1,3,1,3,4,4,5,5,3,1)
table(factor(vec, value))
# 
#  1 77  3 99 
#  4  0  3  0 

Why not just use table?

temp <- table(vec)
temp[names(temp) %in% value]
# vec
# 1 3 
# 4 3 

Another consideration might be to use "data.table", like this:

library(data.table)
data.table(vec, key = "vec")[, .N, by = vec][J(value)]
#    vec N
# 1:   1 4
# 2:   3 3
A5C1D2H2I1M1N2O1R2T1
  • 190,393
  • 28
  • 405
  • 485
  • I had table in mind but it does not take into account the count zero if I provide an element which is not in the vector. The table solution you mentionned does not deal with that :( (nor the data.table, providing NA, but these NA could be replaced by zeros). – Colonel Beauvel Jan 11 '15 at 18:31
  • thanks both for underlying the trick! – Colonel Beauvel Jan 11 '15 at 18:56
  • 1
    Or using `by=.EACHI`: `data.table(vec, key="vec")[J(value), .N, by=.EACHI]` – Arun Jan 13 '15 at 13:15