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

后端 未结 3 1001
深忆病人
深忆病人 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条回答
  •  猫巷女王i
    2021-01-02 07:50

    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))]
    

提交回复
热议问题