如何编写兼容多tibble的硬编码名称标准化函数?
问题分析与解决方案
问题原因
原函数处理向量输入时,filter条件会触发R的向量循环广播机制:当输入名字的数量(如tibble_a的2个)与字典行数(3行)不成倍数时,就会抛出「longer object length is not a multiple of shorter object length」警告。此外,若出现多个匹配项,返回结果长度可能与输入不一致,导致mutate无法正常执行。
解决方案1:逐个处理输入(纯函数风格)
用purrr::map_chr遍历每个输入名字,确保返回结果长度与输入完全一致,同时处理无匹配的情况:
library(tidyverse) name_standardizer <- function(incoming_name){ hardcoded_dictionary <- tribble(~incorrect_name, ~correct_name, "Fries, french", "French fries", "Hamborgar", "Hamburger", "Burger", NA) |> fill(correct_name) map_chr(incoming_name, ~{ # 针对单个名字查询字典 match_result <- hardcoded_dictionary |> filter(incorrect_name == .x | correct_name == .x) |> pull(correct_name) # 取第一个匹配结果,无匹配则返回原名字(可改为NA) first(match_result) %||% .x }) }
使用示例
# 处理tibble_a tibble_a_with_ids_written_well <- tibble_a_with_IDs_written_incorrectly |> mutate(id = name_standardizer(id)) # 处理tibble_c tibble_c_with_ids_written_incorrectly |> mutate(id = name_standardizer(id)) # 执行连接 tibble_a_with_ids_written_well |> left_join(tibble_b, by = "id")
解决方案2:基于left_join的tidyverse风格实现
直接针对tibble操作,通过两次连接匹配字典的incorrect_name和correct_name,确保每行都能得到正确的标准化结果:
library(tidyverse) # 定义全局字典(也可放在函数内部) name_dictionary <- tribble(~incorrect_name, ~correct_name, "Fries, french", "French fries", "Hamborgar", "Hamburger", "Burger", NA) |> fill(correct_name) name_standardizer <- function(df, id_col = id){ id_col <- enquo(id_col) col_name <- quo_name(id_col) df |> # 先匹配错误名称 left_join(name_dictionary, by = set_names("incorrect_name", col_name)) |> # 再匹配正确名称(避免输入已经是标准化名称的情况) left_join(name_dictionary, by = set_names("correct_name", col_name), suffix = c("", "_from_correct")) |> # 合并匹配结果,优先取错误名称匹配到的结果,无匹配则保留原名称 mutate(standardized_id = coalesce(correct_name, correct_name_from_correct, !!id_col)) |> select(-correct_name, -correct_name_from_correct) |> rename(!!col_name := standardized_id) }
使用示例
# 处理tibble_a tibble_a_with_ids_written_well <- tibble_a_with_IDs_written_incorrectly |> name_standardizer() # 处理tibble_c tibble_c_with_ids_written_incorrectly |> name_standardizer()
内容的提问来源于stack exchange,提问作者sas
相关产品推荐
相关产品推荐

