several substitutions in one line R

前端 未结 3 1486
终归单人心
终归单人心 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

    This could also be an evil application for switch:

    set.seed(1492)
    thing <- sample(c(-1, 0, 1), 100, replace=TRUE)
    sapply(as.character(thing), switch, `-1`="no", `0`="maybe", `1`="yes", USE.NAMES=FALSE))
    

    If they are in fact characters already you can leave off the as.character() bit.

    NOTE: I'm not necessarily recommending this, just showing all the possible ways (and this is more of a way out of twisty mazes of ifelse passages).

    IMO factors are the way to go.

提交回复
热议问题