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

如何在RStudio中实现SQL的CASE WHEN THEN逻辑?

在RStudio中实现相同逻辑的代码

首先先构造示例数据集:

# 创建示例数据框
df <- data.frame(
  Field1 = c(1, 2, 3, 4),
  Field2 = c("A", "B", "B", "A"),
  Field3 = c("Y", NA, NA, "Y"),
  Field4 = c(NA, "Y", "N", NA),
  stringsAsFactors = FALSE
)

方法一:使用Base R

直接用ifelse()函数实现条件判断,再筛选需要的列:

# 添加新列NameOfField
df$NameOfField <- ifelse(df$Field1 == 1 & df$Field2 == "A", df$Field3, df$Field4)
# 保留目标列
result_base <- df[, c("Field1", "NameOfField")]
# 查看结果
print(result_base)

方法二:使用tidyverse(dplyr)

这种写法和SQL的CASE WHEN逻辑更贴近,可读性更强:

# 未安装tidyverse时先执行安装
# install.packages("tidyverse")
library(dplyr)

result_tidy <- df %>%
  mutate(NameOfField = case_when(
    Field1 == 1 & Field2 == "A" ~ Field3,
    TRUE ~ Field4
  )) %>%
  select(Field1, NameOfField)

# 查看结果
print(result_tidy)

两种方法最终都会得到预期输出:

Field1NameOfField
1Y
2Y
3N
4Y

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.01 01:42:04