Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Change an integer into a specific string in a data.frame

I have a data frame with two columns. The second column contains only integers. More precisely it contains 0,1,2,3 and some NA's. Something like this:

id1    0
id2    1
id3    0
id4    2
id5    3
id6    1
id7    2
id8    NA

What I'm searching for is a command which changes 0 into ZZT the 1 into ZZU and so on. The NA's should stay as NA's. How could this work?

I tried a for loop in combination with some if-statements but this doesn't work. I know such changing thinks are pretty easy in R but it seems that I have a block in my brain.

like image 352
Tobias Avatar asked Jun 02 '15 16:06

Tobias


2 Answers

This will do it:

  # Setup an example data frame
  df <- data.frame(id=c("id1","id2","id3","id4","id5","id6","id7","id8"),
                 val=c(0,1,0,2,3,1,2,NA))

  # Now setup the translation vector - essentially a lookup table
  trans <- c("ZZT","ZZU","ZZV","ZZW",NA)
  names(trans) <- c(0,1,2,3,NA)

  # Now translate the values into a new column and print it out 
  df$nval <- trans[ as.character(df$val) ]
  df$nval
  # [1] "ZZT" "ZZU" "ZZT" "ZZV" "ZZW" "ZZU" "ZZV" NA 

It uses a named vector as a lookup table. The bracket is actually a subsetting operator, and when you access it with a character vector it subsets using the vector names.

Read Hadley Wickham's great "Advanced R" chapter on subsetting if you don't get this. http://adv-r.had.co.nz/Subsetting.html

like image 174
Mike Wise Avatar answered Oct 31 '22 06:10

Mike Wise


You can map values using the mapvalues function from the plyr package. Using the example data from Mike Wise's answer:

library(plyr)
df$val2 <- mapvalues(df$val,
                           from = c(0,1,2,3,NA),
                           to = c("ZZT", "ZZU", "ZZV", "ZZW", NA))

If you already have the dplyr package loaded (the successor to plyr), call this function usingplyr::mapvalues() as loading plyr on top of dplyr is problematic.

like image 38
Sam Firke Avatar answered Oct 31 '22 06:10

Sam Firke