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