Home > front end >  Split a data frame by median
Split a data frame by median

Time:05-05

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)

CodePudding user response:

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

CodePudding user response:

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

CodePudding user response:

Use split:

split(df, with(df, salary > median(salary)))

$`FALSE`
  salary
1  623.3
2  515.2
3  611.0

$`TRUE`
  salary
4 729.00
5 843.25
  •  Tags:  
  • r
  • Related