[R] counting matches in two vectors

arun smartpink111 at yahoo.com
Thu Jan 23 17:26:53 CET 2014


Hi,
May be this helps:
 z1 <- factor(z)
res1 <- table(z1[cut(w,breaks=c(-Inf,z,Inf),labels=F)])
res1
#
#-5 -4 -3 -2 -1  0  1  2  3  4  5  6  7  8  9 10 11 12 13 14 15 16 17 18 19 20 
# 0  0  0  0  0  0  0  0  0  0  2  1  0  3  1  1  0  1  0  0  0  0  0  0  1  3 
#21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 
# 2  0  0  1  0  0  0  0  0  0  0  0  0  0  0  0  0  0  0  0 
#or
 res2 <- table(z1[findInterval(w,z)])
 identical(res1,res2)
#[1] TRUE



A.K.


Hi all, 
I have the following reproducible example 

z<-c(-5:40) 
w<-c(11, 11, 12, 14, 14, 14, 15, 16, 18, 25, 26, 26, 26, 27, 27, 30) 
 r<-z %in% w 

now r gives me the presence or absence of elements in z that are
 in w but I am interested in getting the number of times each element in
 z appears (or doesn't appear)  in w. I want the dimension of my 
resulting vector to be the same as that of z. How do I do that? 

 Thanks in advance 
 Mintewab



More information about the R-help mailing list