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

Is it possible in base R to replace multiple integers with corresponding strings like a dictionary?

Similar to this question: Replace multiple values in r but: I would like to only use base R and I would like to replace integers, so the named vector solution adopted as below does not work:

testing <- data.frame(
  var1 = c(1, 6, 17)
)

# this is not possible
dict <- c(
  1 = 'ICMP', 
  6 = 'TCP', 
  17 = 'UDP', 
)

testing$var1 <- dict[testing$var1]

I know I can do

testing$var1[testing$var1 == 1] <- "ICMP"
testing$var1[testing$var1 == 6] <- "TCP"
testing$var1[testing$var1 == 17] <- "UDP"

but isn’t there a more convenient way in base R?

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 :

# create named vector dict
dict <- c('ICMP', 'TCP', 'UDP')
names(dict) <- c(1,6,17)
# replace matching values
testing$var2 <- dict[as.character(testing$var1)]

#   var1 var2
# 1    1 ICMP
# 2    6  TCP
# 3   17  UDP
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