hsmith hsmith - 1 year ago 67
R Question

How to define a factor as being above or below its median in R?

So I need to create a factor that defines my 'alt' variable (altitude) as being above or below its median.

I know it should follow this basic shape of creating something new:

conservation$alt.factor <- conservation$alt (..????...)

But I'm just struggling with that last bit.

There must be simple command out there!

Answer Source

Use ifelse():

conservation$alt.factor <- factor(
  ifelse(conservation$alt < median(conservation$alt, na.rm = TRUE), 1, 
   ifelse(conservation$alt > median(conservation$alt, na.rm = TRUE), 2, NA)), 
 1:2, labels = c("below", "above"))

Beware, this setup sets all rows with conservation$alt == median(conservation$alt) as NA. If this is not wanted, just change the last parameter in the ifelse-statement to something else.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download