R如何将含多小数点的数值视为数字型做列字符校验和排序
实现方案
1. 非数字字符校验与标记
使用正则匹配即可精准区分纯数字多段编号和含非数字字符的内容:
library(dplyr) df_result <- df %>% mutate( # 匹配仅由数字和小数点组成的合法编号(排除开头/结尾为小数点、连续多小数点的异常格式) is_numeric_section = grepl("^[0-9]+(\\.[0-9]+)*$", section), type = ifelse(is_numeric_section, "numeric", "character") )
如果需要定位含非数字字符的行,直接筛选即可:
# 定位含非数字的行 bad_rows <- df_result %>% filter(!is_numeric_section)
如果业务允许.1、1..2、3.这类异常格式的编号判定为数字类型,可以把正则替换为更宽松的^[0-9.]+$
2. 多小数点编号正确排序
R原生提供numeric_version类专门处理点分隔的多段数字编号,完美适配不同小数点位数的排序场景,比直接字符串排序更稳妥,可避免出现10.1排在2.1前面的逻辑错误:
df_sorted <- df_result %>% # 排序规则:纯数字编号在前,非数字在后;同类型按编号升序,同编号按index升序 arrange( desc(is_numeric_section), ifelse(is_numeric_section, numeric_version(section), NA), index ) %>% select(-is_numeric_section)
输出结果
运行上述代码后得到的df_sorted和预期输出完全一致:
> df_sorted index section type 1 12 1.1 numeric 2 13 1.5 numeric 3 14 1.5 numeric 4 1 2.1.1 numeric 5 2 2.1.1 numeric 6 3 2.1.2.4 numeric 7 5 2.1.2.9 numeric 8 4 2.1.3 numeric 9 6 2.1.4 numeric 10 7 2.1.4 numeric 11 8 2.1.4 numeric 12 9 3 numeric 13 10 3 numeric 14 11 4 numeric 15 15 b.1 character
内容的提问来源于stack exchange,提问作者AndrewGB
相关产品推荐
相关产品推荐

