[R] Another way to count TRUE

Suharto Anggono Suharto Anggono suharto_anggono at yahoo.com
Wed Jun 7 23:52:24 CEST 2017


Ah, yes, of course.
tabulate(x, 1)
doesn't work, too, in R 3.4.0. Sorry, I didn't actually try.

I thought of an alternative when TRUE count is 2^31 or more. sum(x) returns NA with a warning. sum(as.numeric(x)) works, but requires a quite large memory.

--------------------------------------------
On Thu, 8/6/17, Bert Gunter <bgunter.4567 at gmail.com> wrote:

 Subject: Re: [R] Another way to count TRUE

 Cc: "R-help" <r-help at r-project.org>
 Date: Thursday, 8 June, 2017, 1:09 AM

 Bad idea!

 In R3.3.3 it doesn't even work:

 > y1 <- tabulate(x,1)
 Error in tabulate(x, 1) : 'bin' must be
 numeric or a factor

 ## This
 does:
 >  y1 <-
 tabulate(as.integer(x),1)

 But it's more inefficient than just using
 sum(), even discounting the
 as.integer()
 conversion:

 > y1 <-
 tabulate(as.integer(x),1)
 > y2 <-
 sum(x)
 > identical(y1,y2)
 [1] TRUE

 >
 xx <- as.integer(x)
 >
 system.time(replicate(12,tabulate(xx,1)))
  
  user  system elapsed
   2.488   0.003  
 2.491
 >
 system.time(replicate(12,sum(x)))
    user 
 system elapsed
   0.626   0.001   0.627

 Were you simply unaware of
 sum() or was there some other reason for
 your recommendation?

 Cheers,
 Bert


 Bert
 Gunter

 "The trouble
 with having an open mind is that people keep coming along
 and sticking things into it."
 -- Opus (aka Berkeley Breathed in his
 "Bloom County" comic strip )


 On Wed, Jun 7, 2017 at 9:33 AM, Suharto Anggono
 Suharto Anggono via
 R-help <r-help at r-project.org>
 wrote:
 > To get the number of TRUE in
 logical vector 'x',
 > tabulate(x,
 1)
 > can be used. Actually, it gives
 count of 1, but TRUE as integer is 1. Since R 3.4.0, it
 gives a correct answer, too, when the count is 2^31 or
 more.
 >
 >
 ______________________________________________
 > R-help at r-project.org
 mailing list -- To UNSUBSCRIBE and more, see
 > 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