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.
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.
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
Using match
to create an index vector into the replacement values vector is a "canonical" R approach (using Mike Wise's example)
c("ZZT","ZZU","ZZV","ZZW",NA)[ match( df1$val, c(0,1,2,3,NA))]
[1] "ZZT" "ZZU" "ZZT" "ZZV" "ZZW" "ZZU" "ZZV" NA
If you wanted to replace them "in place" (generally a dangerous option) then this might work:
df$val <- c("ZZT","ZZU","ZZV","ZZW",NA)[ match( df$val, c(0,1,2,3,NA))]