Vector comparison to matrix
1 answers - 927 bytes -

Hi Todd and list,
I see you have received a few suggestions, here's another:
# set up data: your vector and an a 3x300000 matrix with a few
# matching lines:
target<-c(1,2,3)
A<-matrix(sample(1:3,300000,replace=TRUE),ncol=3)
# count matches:
nMatches<-sum(apply(A,1,function(x,target)
all.equal(x,target),target)=="TRUE")
# by applying a simple function, which takes 'target' as an 'extra'
# argument, to the rows of A. The function returns a vector of
# differences and 'TRUE'-s, the latter of which can be counted.
This took 1-2 minutes on my >3 year old laptop.
Siggi
version
_
platform i686-redhat-linux-gnu
arch i686
os linux-gnu
system i686, linux-gnu
status
major 2
minor 0.0
year 2004
month 10
day 04
language R
Yeah, I know, an update is (over)due.
No.1 | | 1629 bytes |
| 
or maybe something like this:
nMatches2 <- sum(!is.na( match(apply(A, 1, paste, collapse = ""),
paste(target, collapse = "")) ))
Best,
Dimitris
Dimitris Rizopoulos
Ph.D. Student
Biostatistical Centre
School of Public Health
Catholic University of Leuven
Address: Kapucijnenvoer 35, Leuven, Belgium
Tel: +32/16/336899
Fax: +32/16/337015
Web:
~m0390867/dimitris.htm
Message
From: "Sigurdur Jonsson" <sigurdur (AT) hafro (DOT) is>
To: <tkredmund98 (AT) hotmail (DOT) com>
Cc: <r-help (AT) stat (DOT) math.ethz.ch>
Sent: Tuesday, August 16, 2005 12:47 PM
Subject: [R] Vector comparison to matrix
Hi Todd and list,
I see you have received a few suggestions, here's another:
# set up data: your vector and an a 3x300000 matrix with a few
# matching lines:
target<-c(1,2,3)
A<-matrix(sample(1:3,300000,replace=TRUE),ncol=3)
# count matches:
nMatches<-sum(apply(A,1,function(x,target)
all.equal(x,target),target)=="TRUE")
# by applying a simple function, which takes 'target' as an 'extra'
# argument, to the rows of A. The function returns a vector of
# differences and 'TRUE'-s, the latter of which can be counted.
This took 1-2 minutes on my >3 year old laptop.
Siggi
version
_
platform i686-redhat-linux-gnu
arch i686
os linux-gnu
system i686, linux-gnu
status
major 2
minor 0.0
year 2004
month 10
day 04
language R
Yeah, I know, an update is (over)due.