Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Difference between " ! " and " - " in r

Tags:

r

negation

Here is a code snippet, where I'm trying to use !:

 demo <- <dataframe>[!which(<dataframe>$<col_name> == 0),]

but it's not giving me the correct output.

When I use - in:

demo <- <dataframe>[-which(<dataframe>$<col_name>== 0),] 

its fetching me the right answer.

Can some one explain why this is so?

like image 466
deepesh Avatar asked Apr 07 '26 17:04

deepesh


2 Answers

So which will return a vector of row indices for which <dataframe>$<col_name> == 0 is satisfied and not a logical (TRUE/FALSE) vector. Hence when you negate that with ! you get nonsense. You are essentially doing this !c(0, 1, 2, 3, 4) which returns TRUE FALSE FALSE FALSE FALSE.

The - sign will remove the rows returned by the which statement, which is what you want.

Alternatively you could do: demo <- <dataframe>[!<dataframe>$<col_name> == 0,]

like image 199
eminik Avatar answered Apr 10 '26 09:04

eminik


Let's take a vector example:

x <- c(1, 10, 30, 5)

I would like to eliminate all the multiples of 10 in this vector. The vector of booleans corresponding to my condition can be computed like this

b <- x %% 10 == 0

If I execute which(b), this will return the indices corresponding to the TRUE values in b, so to exclude all the values that are multiples of 10, I can do

x[ -which(b) ]

But if I use ! (the negation operator) on which(b) instead of - (the command will become x[!which(b)]), the result will be completely wrong, that's because the negation operator can be applied on integers without returning an error: if the integer is equal to 0, it will return TRUE, and if the integer is different from 0, it will return FALSE (try !(-2:2)).

Therefore, if I want the correct result by using !, I need to apply it directly on the vector of booleans

x[ !b ]
like image 38
Vincent Guillemot Avatar answered Apr 10 '26 09:04

Vincent Guillemot