[R] Finding all rows of a matrix equal to vector

Dennis Murphy djmuser at gmail.com
Sat Jul 16 13:51:02 CEST 2011


Hi:

To take this idea a step further,

colSums(apply(unique(A), 1, function(x) apply(A, 1, function(y)
identical(x, y))))
[1] 10  5  5

However, Denis' solution is a bit faster because fewer evaluations are required:

> system.time(replicate(1000,
+ colSums(apply(unique(A), 1, function(x) apply(A, 1, function(y)
identical(x, y))))
+   ))
   user  system elapsed
   1.42    0.00    1.42
> system.time(replicate(1000, {B <- apply(A,1, FUN = function(x)paste(x, collapse = ''))
+ table(B) }))
   user  system elapsed
   0.81    0.00    0.81

Dennis

On Sat, Jul 16, 2011 at 4:03 AM, Berend Hasselman <bhh at xs4all.nl> wrote:
>
> Sebastian Lerch wrote:
>>
>> Hi everyone,
>>
>> my question might be very trivial, but I could not come up with an
>> answer...
>>
>> I want to find out how often a matrix contains a certain vector as row:
>>
>> x1<-c(1,2,3)
>> x2<-c(1,5,6)
>> x3<-c(7,8,9)
>> A<-matrix(c(rep(x1,5),rep(x2,5),rep(x3,5),rep(x1,5)),nrow=20,ncol=3,byrow=T)
>>
>> How can I find out, how many times x1 is a row of A?
>>
>>
>
> v <- apply(A,1, FUN = function(x)identical(x,x1))
> v
> sum(v)
>
> v <- apply(A,1, FUN = function(x)all(zapsmall(x-x1)==0))
> v
> sum(v)
>
>
> Berend
>
>
> --
> View this message in context: http://r.789695.n4.nabble.com/Finding-all-rows-of-a-matrix-equal-to-vector-tp3671606p3671672.html
> Sent from the R help mailing list archive at Nabble.com.
>
> ______________________________________________
> R-help at r-project.org mailing list
> https://stat.ethz.ch/mailman/listinfo/r-help
> PLEASE do read the posting guide http://www.R-project.org/posting-guide.html
> and provide commented, minimal, self-contained, reproducible code.
>



More information about the R-help mailing list