例如,我正在尝试将数据集xpriorjail中第V26列的所有值10,11,12,13,14重命名为“Happy”
此代码由于某种原因无效
xpriorjail$V26[xpriorjail$V26 >= 10 & xpriorjail$V26 <= 12] <- "Happy"
答案 0 :(得分:0)
以下是使用cut
的示例和使用factor
的示例,如我的评论中所述。我建议创建一个新列,而不是覆盖现有列,以便您可以根据需要轻松访问原始数值。
示例数据
set.seed(1)
V26 <- sample(4, 20, replace = TRUE)
V26
# [1] 2 2 3 4 1 4 4 3 3 1 1 1 3 2 4 2 3 4 2 4
选项1:cut
V26Cut <- cut(V26, breaks = c(0, 2, 4),
labels = c("Happy", "Sad"))
V26Cut
# [1] Happy Happy Sad Sad Happy Sad Sad Sad Sad Happy Happy
# [12] Happy Sad Happy Sad Happy Sad Sad Happy Sad
# Levels: Happy Sad
选项2:factor
+ levels
V26Factor <- factor(V26)
levels(V26Factor) <- list(Happy = as.character(1:2), Sad = as.character(3:4))
V26Factor
# [1] Happy Happy Sad Sad Happy Sad Sad Sad Sad Happy Happy
# [12] Happy Sad Happy Sad Happy Sad Sad Happy Sad
# Levels: Happy Sad