Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

R: selecting items matching criteria from a vector

Tags:

r

I have a numeric vector in R, which consists of both negative and positive numbers. I want to separate the numbers in the list based on sign (ignoring zero for now), into two seperate lists:

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

The documentation shows how to do this for selecting rows/columns/cells in a dataframe - but this dosen't work with vectors AFAICT.

How can it be done (without a for loop)?

like image 609
Homunculus Reticulli Avatar asked Apr 08 '12 20:04

Homunculus Reticulli


2 Answers

It 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 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)]
like image 179
Matthew Lundberg Avatar answered Oct 24 '22 11:10

Matthew Lundberg


It can be done by using "square brackets". A new vector is created which contains those values which are greater than zero. Since a comparison operator is used, it will denote values in Boolean. Hence square brackets are used to get the exact numeric 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]
like image 24
Rishabh Avatar answered Oct 24 '22 11:10

Rishabh