如何自动检测各测试项的测量单位是否保持一致
R语言实现代码
library(dplyr) # 提取所有单位不统一的测试项 err_tests <- df %>% group_by(Test) %>% filter(n_distinct(Unit) > 1) %>% distinct(Test) %>% pull(Test) # 根据异常测试项数量输出对应提示 n <- length(err_tests) if(n == 0) { message("所有测试项单位均已统一") } else if(n == 1) { message(sprintf("'%s' test is not in the same unit, conversion is needed", err_tests)) } else { # 处理多异常项的拼接逻辑 test_desc <- paste( paste0("'", err_tests[-n], "'", collapse = ", "), "and", paste0("'", err_tests[n], "'") ) message(sprintf("%s are not in the same unit, conversion is needed", test_desc)) }
效果验证
- 你提供的示例数据运行后输出:
'weight' and 'height' are not in the same unit, conversion is needed
完全符合预期。
2. 若仅单个测试项(比如仅weight)单位不统一,输出:
'weight' test is not in the same unit, conversion is needed
自动适配单复数格式要求。
内容的提问来源于stack exchange,提问作者Stataq
相关产品推荐
相关产品推荐

