我要从数字替换为单词,这是因素。
Ex)
name s1 s2 s3
A 0 1 2
B -2 -1 0
C 0 0 0
D -1 0 1
结果)
name sample1 sample2 sample3
A NO HIGH SHIGH
B SLOW LOW NO
C NO NO NO
D LOW NO HIGH
答案 0 :(得分:0)
您可以通过更改因子向量的levels
来实现。
示例:
> df <- data.frame(s1 = c(0, -2, 0, -1))
> df$s1 <- as.factor(df$s1)
> levels(df$s1) <- c("SLOW", "LOW", "NO")
> df$s1
[1] NO SLOW NO LOW
Levels: SLOW LOW NO
答案 1 :(得分:0)
这里是使用recode_factor
df %>%
mutate_at(
vars(starts_with("s")),
~recode_factor(.x, `-2` = "SLOW", `-1` = "LOW", `0` = "NO", `1` = "HIGH", `2` = "SHIGH"))
# name s1 s2 s3
#1 A NO HIGH SHIGH
#2 B SLOW LOW NO
#3 C NO NO NO
#4 D LOW NO HIGH
或者
library(tidyverse)
df %>%
gather(k, v, -name) %>%
mutate(v = recode_factor(v, `-2` = "SLOW", `-1` = "LOW", `0` = "NO", `1` = "HIGH", `2` = "SHIGH")) %>%
spread(k, v)
# name s1 s2 s3
#1 A NO HIGH SHIGH
#2 B SLOW LOW NO
#3 C NO NO NO
#4 D LOW NO HIGH
df <- read.table(text =
"name s1 s2 s3
A 0 1 2
B -2 -1 0
C 0 0 0
D -1 0 1
", header = T)