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

后端 未结 3 999
深忆病人
深忆病人 2021-01-02 07:02

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           


        
3条回答
  •  悲哀的现实
    2021-01-02 07:51

    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

提交回复
热议问题