Home > Software design >  replace characters with random numbers in R
replace characters with random numbers in R

Time:12-28

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?

CodePudding user response:

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

Or, using R >= 4.1

characters |>
  factor(levels=c("L", "E", "D", "B", "H", "O", "C", "K", "G", "A", "N", "J", 
                  "M", "I", "F"),
         labels=numbers) |>
  as.character() |>
  as.numeric()
# [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))

CodePudding user response:

Creating a reference key and then merging the data

data <- data.frame(char = LETTERS[c(1:10,1:10,11:15)])

key <- data.frame(char = unique(data$char), num = sample(0:99, size=length(unique(data$char)), replace=FALSE))

merge(key, data, on="char")
  • Related