R: selection of criteria for matching elements from a vector

I have a number vector in R that consists of negative and positive numbers. I want to separate the numbers in the list based on the sign (ignoring zero at the moment) into two separate lists:

  • new vector containing only negative numbers
  • another vector containing only positive numbers

The documentation shows how to do this for selecting rows / columns / cells in a data frame - but this does not work with AFAICT vectors.

How to do it (without for loop)?

+6
source share
3 answers

This is done very easily (added check for NaN):

d <- c(1, -1, 3, -2, 0, NaN) positives <- d[d>0 & !is.nan(d)] negatives <- d[d<0 & !is.nan(d)] 

If you want to exclude both NA and NaN, is.na () returns true for both:

 d <- c(1, -1, 3, -2, 0, NaN, NA) positives <- d[d>0 & !is.na(d)] negatives <- d[d<0 & !is.na(d)] 
+10
source

This can be done using "square brackets". A new vector is created that contains those values ​​that are greater than zero. Since the comparison operator is used, it will denote the values ​​in Boolean. Therefore, square brackets are used to get the exact numerical value.

 d_vector<-(1,2,3,-1,-2,-3) new_vector<-d_vector>0 pos_vector<-d_vector[new_vector] new1_vector<-d_vector<0 neg_vector<-d_vector[new1_vector] 
+1
source
Package

purrr contains some useful functions for filtering vectors:

 library(purrr) test_vector <- c(-5, 7, 0, 5, -8, 12, 1, 2, 3, -1, -2, -3, NA, Inf, -Inf, NaN) positive_vector <- keep(test_vector, function(x) x > 0) positive_vector # [1] 7 5 12 1 2 3 Inf negative_vector <- keep(test_vector, function(x) x < 0) negative_vector # [1] -5 -8 -1 -2 -3 -Inf 

You can also use the discard function

0
source

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


All Articles