0

I have a table split into height and sex. I am able to find the median of the data as a whole but do not know how to find the median of the individual groups. can anyone help?

2 Answers2

0

In base R, you can use aggregate:

aggregate(d$Height, by = list(d$sex), FUN = median)

  Group.1  x
1       F 49
2       M 65

Using dplyr package:

library(dplyr)
d %>% group_by(sex) %>% summarise(Median = median(Height))

# A tibble: 2 x 2
  sex   Median
  <fct>  <int>
1 F         49
2 M         65

Using data.table package:

library(data.table)
setDT(d)
d[, .(Height = median(Height)), by = .(sex)]

   sex Height
1:   F     49
2:   M     65

Reproducible example

d <- data.frame(Height = sample(1:100, 100, replace = TRUE),
                 sex = sample(c("M","F"),100, replace = TRUE))
dc37
  • 15,840
  • 4
  • 15
  • 32
0

Using tapply() in Rbase

d=data.frame(c(10,11,23,15,16),c("M","M","F","M","F"))
names(d)=c("Height","Gender")
tapply(d$Height,d$Gender,median)

Output

  F    M 
19.5 11.0 
AlexWithYou
  • 399
  • 1
  • 4
  • 14