[R] [External] NAs are removed

Richard M. Heiberger rmh @end|ng |rom temp|e@edu
Fri Jan 14 23:37:45 CET 2022


this is a related issue.  For this example, the ifelse statement is 10 times slower than
a much simpler != comparison.


> tmp <- sample(1:2, 40, TRUE)
> tmp
 [1] 2 2 2 2 1 2 1 2 1 1 1 1 1 2 1 2 2 1 1 2 1 2 2 2 1 1 1 2 2 1 2 1 1 1 2 1 2 1 2 2
> ifelse(tmp==2, 0, 1)
 [1] 0 0 0 0 1 0 1 0 1 1 1 1 1 0 1 0 0 1 1 0 1 0 0 0 1 1 1 0 0 1 0 1 1 1 0 1 0 1 0 0
> as.numeric(tmp != 2)
 [1] 0 0 0 0 1 0 1 0 1 1 1 1 1 0 1 0 0 1 1 0 1 0 0 0 1 1 1 0 0 1 0 1 1 1 0 1 0 1 0 0
>??micro
> microbenchmark::microbenchmark(ifelse=ifelse(tmp==2, 0, 1), notequal=as.numeric(tmp !=2))
Unit: nanoseconds
     expr  min   lq    mean median   uq   max neval cld
   ifelse 2952 3239 3542.81 3382.5 3567 12464   100   b
 notequal  205  287  348.09  328.0  369  1599   100  a 


> 
> From: Neha gupta <neha.bologna90 using gmail.com>
> Sent: Friday, January 14, 2022 5:11 PM
> To: Ebert,Timothy Aaron <tebert using ufl.edu>
> Cc: Jim Lemon <drjimlemon using gmail.com>; r-help mailing list <r-help using r-project.org>
> Subject: Re: [R] NAs are removed
> 
> [External Email]
> I have a variable in dataset "CA", which has the following values:
> 
> [1] 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1
> [40] 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2
> 
> then I used this statement
> 
> prot <- ifelse(ts$CA == '2', 0, 1)
> 
> Is the problem exist here?
> 



More information about the R-help mailing list