Create Group Column

I'm four months into R and have a requirement which seems simple, yet the solutions I see are quite involved. Looking for a suggestion on how I can "walk" a column of data in a dataframe and create an adjacent column which contains a value based on a fixed criteria without having to write long ifelse statements. Here's the column I'd like to walk:

4
12
13
21
35
42
43
44
51

Starting at 4, I'd like to add 10 and assign values of "A" to any values falling between or equal to 4 and less than 14. I then want to assign "B" to any values falling between 14 and 24, then "C" to values between 24 and 34 (note there are none), etc. The results should look like this (two columns) given the entered value of 10. My use case has thousands of records to manage.

4 A
12 A
13 A
21 B
35 D
42 D
43 D
44 E
51 E

Any suggestions are appreciated!

LETTERS is a predefined vector of the upper case letters and %/% is the operator for integer division.

DF <- data.frame(VALS = c(4,12,13,21,35,42,43,44,51))
DF$LETTER <- LETTERS[((DF$VALS - 4) %/% 10) + 1]
DF
#>   VALS LETTER
#> 1    4      A
#> 2   12      A
#> 3   13      A
#> 4   21      B
#> 5   35      D
#> 6   42      D
#> 7   43      D
#> 8   44      E
#> 9   51      E

Created on 2020-09-14 by the reprex package (v0.3.0)

1 Like

good idea, but I have thousands of records and I believe letters is maxed at 26? I'll have integers over 26

You can construct your own vector of labels. I used LETTERS because I saw A - E as the labels you used. What will you use after Z?

ok, good point. I can work with this construct so thanks.