'Split a data frame by median

I would like to divide my data based on the median into high and low. I want to put it in one column.

df <- data.frame(salary = c(623.3,515.2,611.0,729.0,843.25), stringsAsFactors = FALSE)
r


Solution 1:[1]

Like this?

library(dplyr)

df <-  data.frame(salary = c(623.3,515.2,611.0,729.0,843.25), stringsAsFactors = FALSE) %>% 
  mutate(indicator = ifelse(salary > median(salary),"High","Low"))

df_low <- df %>% filter(indicator == "Low")
df_high <- df %>% filter(indicator == "High")

Solution 2:[2]

You can do it like this:

df$median <- ifelse(df$salary > median(df$salary), 'high', 'low')

df
#>   salary median
#> 1 623.30    low
#> 2 515.20    low
#> 3 611.00    low
#> 4 729.00   high
#> 5 843.25   high

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Julian
Solution 2 Aron