Homunculus Reticulli Homunculus Reticulli - 4 years ago 131
R Question

R: selecting items matching criteria from a vector

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)?

Answer Source

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)]
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download