0

Given the following

group
0
1
2
3
4
5
6
7
8
9
10

What is an elegant way to create a new column level to make data look like the following

group  level
0       none
1       low
2       low
3       low
4       med
5       med
6       med
7       high
8       high
9       high
10      very_high

my current solution is to input each of the values in mutate. Is there a better way?

Alex
  • 2,603
  • 4
  • 40
  • 73
  • 1
    I think `cut` is the way to go for a numeric vector like this, but also see `forcats::fct_collapse`. – aosmith Nov 03 '17 at 19:29

2 Answers2

1

You can use cut:

df$level <- cut(df$group, breaks = c(0,1,4,7,10,Inf), right = F, labels = c('none', 'low', 'med', 'high', 'very_high'))

df
#   group     level
#1      0      none
#2      1       low
#3      2       low
#4      3       low
#5      4       med
#6      5       med
#7      6       med
#8      7      high
#9      8      high
#10     9      high
#11    10 very_high
Psidom
  • 209,562
  • 33
  • 339
  • 356
1
df$level =factor(as.character(ceiling(df$group/3)),labels = c('none', 'low', 'med', 'high', 'very_high'))
df
   group     level
1      0      none
2      1       low
3      2       low
4      3       low
5      4       med
6      5       med
7      6       med
8      7      high
9      8      high
10     9      high
11    10 very_high
BENY
  • 317,841
  • 20
  • 164
  • 234