is there a way to execute if statement for null values

Viewed 43

Not sure why i am getting this error. Can we not execute this statement

asd <- c()
asd1 <- c()

if(asd == asd1)
{
  pr <- 0
} else{
  pr <- 1
}
Error in if (asd == asd1) { : argument is of length zero

Can we not execute null values here? Because is asd is also 0 and asd1 is also 0. Also I do not need to use length(asd) == length(asd1). But asd == asd1 should work right?

3 Answers

No, you are trying to compare nothing to nothing. if you don't want to use length but actually want to check if both vectors are the same:

identical(asd,asd1)

Use all function,

asd <- c()
asd1 <- c()

if(all(asd == asd1)){
  pr <- 0
} else{
  pr <- 1
}

> pr
[1] 0

like most of the r functions, "==" is a vectorial function in R. Therefore ==(x,y) compares the elements of x and y, returning a vector of the same size.

As stated by dvd280, identical is the "strict equality" between objects, that test that everything is exactly the same (by everything i mean everything ; every element of the structure must be the same). Note : it doesn't check that the 2 objects are stored at the same place in the memory.

all.equal (with some arguments) checks the equality of everyone.

vectorial logic is something that is often seen in R ; by example

c(TRUE,TRUE)&c(TRUE,FALSE)

returns

c(TRUE,FALSE)

which is something fine because it is a language made for statistics : it relies on vectors, not variables which, in fact, in r, are length 1 vectors.

Related