Reputation: 68
I want to write a function,Determine the input is equal to 1, but The input maybe includes (NA NULL).
> equals1 <- function(x){
+ return(x==1)
+ }
> equals1(1)
[1] TRUE
> equals1(Inf)
[1] FALSE
> equals1(NA)
[1] NA
> equals1(NULL)
logical(0)
> equals1(NaN)
[1] NA
I want is as follows:
equals1<-function(x){
if(is.null(x)){
return(FALSE)
}else if(is.na(x)){
return(FALSE)
}else{return(x==1)}
}
c(equals1(1),equals1(Inf),equals1(NA),equals1(NULL),equals1(NaN))
# [1] TRUE FALSE FALSE FALSE FALSE
Is there a simple function? Thanks!
Upvotes: 0
Views: 67
Reputation: 615
according Numeric comparison difficulty in R this function can do it easily. note that identical(tan(pi/4),1) returns false.
identical(tan(pi/4),1)
#[1] FALSE
eq<-function(x,y){
isTRUE(all.equal(x, y))
}
eq(tan(pi/4),1)
#[1] TRUE
eq(3,1)
#[1] FALSE
eq(NA,1)
#[1] FALSE
eq(1, NaN)
#[1] FALSE
eq(1,1)
#[1] TRUE
eq(Inf,1)
#[1] FALSE
eq(NA,1)
#[1] FALSE
eq(NULL,1)
#[1] FALSE
Upvotes: 1
Reputation: 12084
identical
can do this.
identical(1, 1)
#> [1] TRUE
identical(1, Inf)
#> [1] FALSE
identical(1, NA)
#> [1] FALSE
identical(1, NULL)
#> [1] FALSE
identical(1, NaN)
#> [1] FALSE
Created on 2019-03-08 by the reprex package (v0.2.1)
You could write a simple wrapper like this:
equals1 <- function(x)identical(x, 1)
c(equals1(1),equals1(Inf),equals1(NA),equals1(NULL),equals1(NaN))
#> [1] TRUE FALSE FALSE FALSE FALSE
Created on 2019-03-08 by the reprex package (v0.2.1)
Upvotes: 3