You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

R语言中如何将列中0替换为None、其余值替换为others?

解决方案

方法1:用dplyr::case_when(逻辑最直观)

不管原列是字符型还是数值型,都能通过条件判断快速赋值:

library(dplyr)

# 假设数据框为df,目标列是col
df <- df %>%
  mutate(new_col = case_when(
    col == "0" ~ "None",  # 原列是字符型"0"时用这个
    # 若原列是数值型,替换成:col == 0 ~ "None",
    TRUE ~ "others"       # 所有其他值统一设为"others"
  ))

方法2:正确使用forcats::fct_collapse

你之前没用到other_level参数,这个参数正好用来统一处理所有未指定的类别:

library(forcats)

# 先转成因子(如果原列不是因子),再折叠类别
df$new_col <- fct_collapse(
  as.factor(df$col),
  None = "0",  # 将"0"映射为"None"
  other_level = "others"  # 剩余所有类别归为"others"
)

方法3:Base R 原生实现(无需额外包)

用基础包的ifelse就能完成,简单高效:

# 原列是字符型的情况
df$new_col <- ifelse(df$col == "0", "None", "others")

# 原列是数值型的情况
df$new_col <- ifelse(df$col == 0, "None", "others")

内容的提问来源于stack exchange,提问作者Philipp

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.05 04:32:30