简体   繁体   中英

Tertile and quantile split in R studio

I am seeking some help on how to convert one of my columns in my data frame into others based on it which are tertiles and quartiles. I wish to have one group of the two lower tertiles for the tertile split and 3 of the lower quartiles for the quartile split. I am assessing the threshold effect and would appreciate any help on this. For example this is the code i used for my median split.

honourswork %>% mutate(medianpcr = median(PCR.x)) %>%
  mutate(lowmedian = ifelse(PCR.x <= medianpcr, 1, 0)) -> honourswork

You can use quantile and cut to bin the data.

honourswork %>%
  mutate(
    lowmedian = as.integer(PCR.x <= median(PCR.x)),
    tertile = cut(PCR.x, quantile(PCR.x, c(0, (2:3)/3)), 
                  labels = c("two lower tertiles", "upper tertile")),
    quartile = cut(PCR.x, quantile(PCR.x, c(0, (3:4)/4)), 
                   labels = c("three lower quartiles", "upper quartile"))
  )

Edit

To have the tertiles and quartiles groups as integers 0/1 instead of factors, run the following.

honourswork %>%
  mutate(
    lowmedian = as.integer(PCR.x <= median(PCR.x)),
    tertile = findInterval(PCR.x, quantile(PCR.x, c(0, (2:3)/3))), 
    quartile = findInterval(PCR.x, quantile(PCR.x, c(0, (3:4)/4)))
  ) %>%
  mutate(
    tertile = if_else(tertile == 2L, 0L, tertile),
    quartile = if_else(quartile == 2L, 0L, quartile)
  )

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM