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

在R中如何优先取非NA折扣价、无折扣则取原价计算商品最终售价

R语言实现商品最终售价计算

首先构造示例数据集:

df <- data.frame(
  Item = c("A", "B", "C", "D", "E", "F"),
  Price = c(5.70, 4.50, 5.67, 3.23, 1.24, 4.25),
  Discounted_price = c(4.00, NA, 3.50, 2.75, NA, NA)
)

方法1:基础R实现(无需额外安装包)

使用内置ifelse加is.na判断即可实现需求:

# 替换Price列为最终售价
df$Price <- ifelse(!is.na(df$Discounted_price), df$Discounted_price, df$Price)
# 提取指定列得到结果
result <- df[, c("Item", "Price")]

方法2:dplyr包实现(代码更简洁易读)

利用dplyr内置的coalesce函数,可直接返回参数列表中第一个非NA的值,完全匹配需求逻辑:

# 加载dplyr包
library(dplyr)

result <- df %>%
  mutate(Price = coalesce(Discounted_price, Price)) %>%
  select(Item, Price)

运行上述任意一种方法后,打印result即可得到你需要的输出结果。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.28 20:36:01