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

R语言中如何基于多条件为dataframe定义新列

R实现指定行赋值新列的两种方案

前置示例数据构造

set.seed(123) # 固定随机种子保证结果可复现
data <- data.frame(
    id = 1:10,
    Question = rep("Q1", 10),
    Answer = sample(5, 10, replace = TRUE)
)

方案1:基础R实现

场景A:按行号筛选目标行(对应示例中第2、5行赋值需求)

# 定义目标行号
target_rows <- c(2,5)
# 初始化新列为NA
data$new_values <- NA
# 仅对目标行按规则赋值
data$new_values[target_rows] <- data$Answer[target_rows] * 4

场景B:按题号筛选目标行+自定义映射规则

如果需要针对指定题号的所有行赋值,且Answer和新值没有数学关系,可用命名向量做映射:

# 定义需要处理的目标题号
target_questions <- c("Q2", "Q5", "Q10")
# 定义Answer到新值的映射规则:1→0,2→1,5→20
map_rule <- c("1" = 0, "2" = 1, "5" = 20)
# 初始化新列为NA
data$new_values <- NA
# 筛选目标题号行,按映射规则赋值
match_idx <- data$Question %in% target_questions
data$new_values[match_idx] <- map_rule[as.character(data$Answer[match_idx])]

方案2:tidyverse实现(代码更简洁易读)

library(dplyr)

场景A:按行号筛选赋值

data <- data %>%
  mutate(new_values = case_when(
    row_number() %in% c(2,5) ~ Answer * 4,
    .default = NA
  ))

场景B:按题号筛选+自定义映射赋值

map_rule <- c("1" = 0, "2" = 1, "5" = 20)
data <- data %>%
  mutate(new_values = case_when(
    Question %in% c("Q2", "Q5", "Q10") ~ map_rule[as.character(Answer)],
    .default = NA
  ))

两种方案运行后输出结果和预期格式完全一致。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.21 08:36:03