Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Replacing a vector of numbers by specific characters in a data.frame

I have the following data:

df <- data.frame(a = c(5,5,8,4,2,1,9,8,7,3,6)

I want add a new column to name the numbers based on the following:

names <- c(1 = "A", 2 = "B", 3 = "C", 4 = "D", 5 = "E", 
6 = "F", 7 = "G", 8 = "H", 9 = "I", 10 = "J", 11 = "K")

The desired output is:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

   a  b
1  5  E
2  5  E
3  8  H
4  4  D
5  2  B
6  1  A
7  9  I
8  8  H
9  7  G
10 3  C
11 6  F

>Solution :

If you are continuing from your previous question where you want to divide the data by range, you can use labels option in cut.

Using the previous example –

range <- c(0, seq(19, max(DF$AGE) + 10, 10))
labs <- paste(range[-length(range)] + 1, range[-1], sep = '-')
labs
#[1] "1-19"  "20-29" "30-39" "40-49" "50-59" "60-69"

transform(DF, GROUP = cut(AGE, c(0, seq(19, max(AGE) + 10, 10)), labels = labs))

#    NAME AGE GROUP
#1   Gait  33 30-39
#2    Roc  43 40-49
#3     Bo  37 30-39
#4  Hernd  45 40-49
#5    Bet  44 40-49
#6    Oln  35 30-39
#7    Gai  22 20-29
#8   Rock  30 30-39
#9    Mil  38 30-39
#10  Arli  23 20-29
#11    Re  45 40-49
#12  Fred  43 40-49
#13    Ro  67 60-69
#14  Rock  43 40-49
#15 Wheat  28 20-29
#16 Germa  47 40-49
#17  Rock  16  1-19
#18  Nort  29 20-29
#19  Arli  22 20-29
#20 Rockv  31 30-39
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading