hsmith hsmith - 1 month ago 7
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

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.