R语言修改dataframe中分类变量chanel的kw取值为sea的方法
R 修改dataframe指定列特定值的操作方法
这里有两种常用实现方案,均不会改动原dataframe除目标值外的其他内容:
方案1:基础R实现(无需加载额外依赖包)
直接通过逻辑匹配定位目标单元格替换即可:
tvdata$chanel[tvdata$chanel == "kw"] <- "sea"
如果你的chanel列为因子(factor)类型,推荐直接修改因子水平,效率更高:
levels(tvdata$chanel)[levels(tvdata$chanel) == "kw"] <- "sea"
方案2:dplyr 风格实现(适合tidyverse生态用户)
先加载dplyr包,再通过管道操作完成替换:
library(dplyr) # 方法A:用ifelse判断替换 tvdata <- tvdata %>% mutate(chanel = ifelse(chanel == "kw", "sea", chanel)) # 方法B:用replace函数更直观 tvdata <- tvdata %>% mutate(chanel = replace(chanel, chanel == "kw", "sea"))
内容的提问来源于stack exchange,提问作者N_I
相关产品推荐
相关产品推荐

