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

replace characters with random numbers in R

I have data list in characters. I would like to replace these characters with random numbers.

characters<-LETTERS[c(1:10,1:10,11:15)]
numbers <- floor(runif(16, min = 1, max = 100))

How do I add the numbers into each characters?

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

>Solution :

Simply use factors and convert to numeric.

as.numeric(as.character(factor(characters, labels=numbers)))
# [1] 91 93 29 83 64 52 73 14 66 70 91 93 29 83 64 52 73 14 66 70 46 72 93 26 46

You also may read the levels= in in arbitrary order.

as.numeric(as.character(factor(characters, 
       levels=c("L", "E", "D", "B", "H", "O", "C", "K", "G", "A", "N", "J", 
                "M", "I", "F"),
       labels=numbers)))
# [1] 70 83 73 29 93 46 66 64 26 72 70 83 73 29 93 46 66 64 26 72 14 91 93 46 52

Data:

set.seed(42)
characters <- LETTERS[c(1:10, 1:10, 11:15)]
numbers <- floor(runif(length(unique(characters)), min=1, max=100))
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