首页 > 解决方案 > 突变改变所有值

问题描述

我正在尝试使用以下代码执行突变:

set <- c('1 star', '2 stars', '3 stars', '4 stars', '5 stars')
set <- as.data.frame(set)
names(set) <- c('score')
set$score <- as.factor(set$score)
set <- set %>% mutate(score = ifelse(score == '1 star', 1, score))

我期望代码将包含值的单元格更改1 star1,如果值不是1 star,我希望它保持原样。但是,它似乎更改了所有行中的值,包括那些具有其他值的单元格1 star

我的推理出了什么问题?

标签: rdplyr

解决方案


替换时将值更改为字符。

library(dplyr)

set <- set %>% mutate(score = ifelse(score == '1 star', 1, as.character(score)))

#    score
#1       1
#2 2 stars
#3 3 stars
#4 4 stars
#5 5 stars

推荐阅读