Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Count the occurrence of one vector's values in another vector

Tags:

r

count

vector

I have 2 vectors

v1 <- c(164,38,20,19,163,22,21,4) 
v2 <- c(0,21,164,60,59,58,57,22,5,3,164,38,22,20,4,164,38,20,19,3,4,19,20,164,21,3,4,19,22,20,164,163,20,19,3)

I would like to count the occurrence of the numbers in vector 1 in vector 2. I tried to do it with a loop but it didn't quite worked because of the format of the table.

a<-table(v2)
occurrence<-numeric()
for(i in v1){
   occurrence[i]<-a[names(a)==v1[i]]
}
occurSum<-sum(occurrence)

Do you know a way to do this preferably without using a loop?

like image 228
user3584444 Avatar asked Mar 19 '15 10:03

user3584444


2 Answers

Perhaps you are looking for something like a combination of table and %in%:

> table(v2[v2 %in% v1])

  4  19  20  21  22  38 163 164 
  3   4   5   2   3   2   1   5 

Or, building on your attempt, you might try:

tv2 <- table(v2)
tv2[match(v1, names(tv2))]
like image 63
A5C1D2H2I1M1N2O1R2T1 Avatar answered Oct 13 '22 10:10

A5C1D2H2I1M1N2O1R2T1


Try:

vec1 = c(2,3,4,5)
vec2 = c(1,2,2,3,3,3,3,4,5,5,5,6,7,7)

rle(sort(vec2[vec2 %in% vec1]))

#Run Length Encoding
#  lengths: int [1:4] 2 4 1 3
#  values : num [1:4] 2 3 4 5
like image 22
Colonel Beauvel Avatar answered Oct 13 '22 10:10

Colonel Beauvel