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

如何用dplyr在R中按n<=20的条件重编码CountryOther变量?

用dplyr实现CountryOther变量的条件重编码

不需要手动逐个指定国家,直接通过条件逻辑结合mutate就能完成需求,mutate_at用于批量处理多个变量,这里只操作单个变量,用mutate更简洁。

解决方案1:使用if_else实现条件替换

# 先将CountryOther设为Country的副本(如果需要保留原Country字段的话)
dataExtended <- dataExtended %>%
  mutate(CountryOther = Country) %>%
  # 当n<=20时,把CountryOther改为"Other",否则保留原有值
  mutate(CountryOther = if_else(n <= 20, "Other", CountryOther))

解决方案2:使用case_when(适合扩展更复杂的条件)

如果后续需要添加更多条件判断,case_when会更灵活:

dataExtended <- dataExtended %>%
  mutate(CountryOther = Country) %>%
  mutate(CountryOther = case_when(
    n <= 20 ~ "Other",
    TRUE ~ CountryOther  # 所有不满足上面条件的情况,保持原值
  ))

关于你手动重编码未生效的原因

你之前的代码没有将管道处理后的结果重新赋值给dataExtended,dplyr的管道操作默认返回新的数据框,不会直接修改原数据集。如果要手动指定国家,需要改成这样:

dataExtended <- dataExtended %>% 
  mutate(CountryOther = Country) %>%
  mutate(CountryOther = recode(CountryOther,
                               China = "Other", 
                               Mexico = "Other", 
                               Slovakia = "Other",
                               Bulgaria = "Other", 
                               Canada = "Other", 
                               Croatia = "Other", 
                               Uruguay = "Other", 
                               Georgia = "Other", 
                               Turkey = "Other", 
                               Moldova = "Other", 
                               Slovenia = "Other", 
                               Hungary = "Other", 
                               Switzerland = "Other", 
                               Greece = "Other", 
                               Israel = "Other", 
                               Lebanon= "Other"))

不过这种方式效率低,不如条件判断灵活,当国家数量多或者n的阈值变化时,需要手动修改代码,推荐用前面的条件替换方法。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.06 14:32:21