several substitutions in one line R

前端 未结 3 1462
终归单人心
终归单人心 2020-12-10 13:07

I have a column in a dataframe in R with values \"-1\",\"0\",\"1\". I\'d like to replace these values with \"no\", \"maybe\" and \"yes\" respectively. I\'ll do this by usi

3条回答
  •  囚心锁ツ
    2020-12-10 14:07

    factor is commonly used for this type of task, and leads to some pretty easily readable code:

    vec <- c(0, 1, -1, -1, 1, 0)
    vec
    # [1]  0  1 -1 -1  1  0
    
    factor(vec, levels = c(-1, 0, 1), labels = c("no", "maybe", "yes"))
    # [1] maybe yes   no    no    yes   maybe
    # Levels: no maybe yes
    

    If you want just the character output, wrap it in as.character.


    If the column values are already strings, you just modify the levels argument in factor to use as.character:

    vec2 <- as.character(c(0, 1, -1, -1, 1, 0))
    vec2
    # [1] "0"  "1"  "-1" "-1" "1"  "0" 
    
    factor(vec2, levels = as.character(c(-1, 0, 1)), labels = c("no", "maybe", "yes"))
    # [1] maybe yes   no    no    yes   maybe
    # Levels: no maybe yes
    

提交回复
热议问题