基于命名向量实现价格对应价目表匹配的R语言函数开发需求
问题需求
给定一个由单价和对应价目表名称组成的命名向量,编写R语言函数为数据集新增一列,标注数据集中价格所属的价目表名称。需满足以下要求:
- 处理缺失值(NA)及未在价目表中的价格,返回
'not found' - 价目表存在重复单价条目时,取第一个匹配的价目表名称
示例数据
pricelist = rlang::set_names( x = c(11.12, 11.45, 14.45, 12.66, 12.96, 14.45), nm = c("1", "2", "3", "4", "5", "6")) data = tibble( article = rep("article 34", 10), price = c(11.12, NA, 11.45, 11.45, 11.45, 14.45, NA, 20, 12.96, 12.66))
解决方案
先对重复单价的价目表条目去重(保留第一个出现的对应关系),再通过映射实现匹配:
pricelist_fn <- function(price_vec, pricelist) { # 去重:保留价目表中每个单价第一次出现的名称 unique_pricelist <- pricelist[!duplicated(pricelist)] # 映射匹配,未匹配/NA返回指定值 dplyr::recode(price_vec, !!!unique_pricelist, .default = 'not found', .missing = 'not found') }
验证结果
加载dplyr后调用函数,查看输出:
library(dplyr) data %>% mutate(pricelist = pricelist_fn(price = price, pricelist = pricelist))
输出结果:
# A tibble: 10 x 3 article price pricelist <chr> <dbl> <chr> 1 article 34 11.1 1 2 article 34 NA not found 3 article 34 11.4 2 4 article 34 11.4 2 5 article 34 11.4 2 6 article 34 14.4 3 7 article 34 NA not found 8 article 34 20 not found 9 article 34 13.0 5 10 article 34 12.7 4
内容的提问来源于stack exchange,提问作者mcmurphy
相关产品推荐
相关产品推荐

