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

如何基于另一变量的值重新编码R数据框中的变量?

解决方案

你可以通过以下几种方式实现需求:

方法1:Base R 原生实现

嵌套ifelse语句

直接通过条件判断替换对应值:

df$fruit <- ifelse(
  df$fruit == "other" & df$specify == "red delicious", 
  "apple",
  ifelse(
    df$fruit == "other" & df$specify == "navel", 
    "orange", 
    df$fruit
  )
)

映射表替换

先建立specify到目标fruit的映射关系,再批量替换:

# 创建映射表
spec_map <- c("red delicious" = "apple", "navel" = "orange")
# 定位需要替换的行并赋值
df$fruit[df$fruit == "other"] <- spec_map[df$specify[df$fruit == "other"]]

方法2:Tidyverse (dplyr) 实现

使用dplyr的case_when函数,逻辑更清晰易读:

library(dplyr)

df <- df %>%
  mutate(fruit = case_when(
    fruit == "other" & specify == "red delicious" ~ "apple",
    fruit == "other" & specify == "navel" ~ "orange",
    TRUE ~ fruit  # 其他情况保持原fruit值不变
  ))

修改后的数据框结果

执行上述任意方法后,数据框会更新为:

> df
  record   fruit      specify
1      1   apple            
2      2  orange            
3      3   apple red delicious
4      4   apple            
5      5  orange            
6      6  orange        navel

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.27 17:25:03