'How to create tertile in R
I Have a column in my dataframe called Score
for example
DF$Score<-(1.2,2,2,3.2,4.4,4.5,2.5,6.7,8.9,4.8)
I want to make a new column containing tertiles of this column (called Low, Medium and High). How to do that in R? I knoe quantile function but i am asking about tertiles here.
Solution 1:[1]
DF = data.frame(Score = c(1.2,2,2,3.2,4.4,4.5,2.5,6.7,8.9,4.8))
# Find tertiles
vTert = quantile(DF$Score, c(0:3/3))
# classify values
DF$tert = with(DF,
cut(Score,
vTert,
include.lowest = T,
labels = c("Low", "Medium", "High")))
# The result
> DF
Score tert
1 1.2 Low
2 2.0 Low
3 2.0 Low
4 3.2 Medium
5 4.4 Medium
6 4.5 Medium
7 2.5 Low
8 6.7 High
9 8.9 High
10 4.8 High
Solution 2:[2]
Another option would be to use dplyr
:
df %>%
mutate(tertiles = ntile(Score, 3)) %>%
mutate(tertiles = if_else(tertiles == 1, 'Low', if_else(tertiles == 2, 'Medium', 'High'))) %>%
arrange(Score)
# Score tertiles
# 1 1.2 Low
# 2 2.0 Low
# 3 2.0 Low
# 4 2.5 Low
# 5 3.2 Medium
# 6 4.4 Medium
# 7 4.5 Medium
# 8 4.8 High
# 9 6.7 High
# 10 8.9 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 | mattek |
Solution 2 | AlexB |