How to choose only positive values?

I have a dataset that contains positive, negative, and also NA values. How can I select values ​​with a positive value using a script? I would also like to replace the negative numbers with NA and leave the NA values ​​as they are.

+8
source share
2 answers

You can use which function:

 sample <- c(1, 2, -7, NA, NaN) sample[which(sample > 0)] [1] 1 2 

For negative values, assign NA.

Using which :

 sample[which(sample < 0)] <- NA 
+7
source

You can try the following command:

 > x<-c(1,2,3,-5) > x[x>0] [1] 1 2 3 

would return all positive values.
To replace negative numbers, use NA

 > x <- ifelse(x<0, NA,x) > x [1] 1 2 3 NA 

Another way to select positive values ​​would be to use sign

 x[sign(x) == 1] 

and we can combine them in Filter

 Filter(function(i) i > 0, x) Filter(function(i) sign(i) == 1, x) 
+3
source

Source: https://habr.com/ru/post/1212932/


All Articles