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

使用case_when按索引替换值时孤立值返回NA的解决方法(dplyr)

解决方案

先明确目标映射规则:

  • Vanilla → 1
  • Grape → 2
  • Peach → 3
  • Passion Fruit → 4
  • Watermelon → NA

在dplyr/magrittr框架内,以下几种方法都能解决问题:

方法1:用dplyr::recode()快速映射

recode()天生适合这种固定值匹配,未指定的默认返回NA,刚好符合需求:

library(dplyr)

df_2 <- df_2 %>%
  mutate(x_num = recode(x,
                        "Vanilla" = 1,
                        "Grape" = 2,
                        "Peach" = 3,
                        "Passion Fruit" = 4))

执行后结果:

x y x_num
1       Vanilla A     1
2         Grape B     2
3         Peach C     3
4 Passion Fruit D     4
5       Vanilla E     1
6         Peach F     3
7         Grape G     2
8    Watermelon H    NA
9 Passion Fruit I     4

方法2:修正case_when()的写法

如果之前用case_when失效,大概率是没写全匹配规则或忽略了类型统一。正确写法如下:

df_2 <- df_2 %>%
  mutate(x_num = case_when(
    x == "Vanilla" ~ 1,
    x == "Grape" ~ 2,
    x == "Peach" ~ 3,
    x == "Passion Fruit" ~ 4,
    TRUE ~ NA_real_  # 未匹配项返回NA,必须用NA_real_保证数值类型统一
  ))

方法3:因子转数值(适合顺序匹配场景)

如果映射数值刚好对应水果的排序,可先转因子再转数值,不在指定水平内的值会自动变成NA:

df_2 <- df_2 %>%
  mutate(x_num = as.numeric(factor(x, levels = c("Vanilla", "Grape", "Peach", "Passion Fruit"))))

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.25 18:27:29