R语言使用fread读取CSV时处理特殊字符转换字符列为数值列方法
问题背景
- 运行环境:R 4.2.0、data.table 1.14.2
- 初始操作:调用
fread()读取CSV文件时已指定sep=','、dec='.'、na.strings = c('', 'NA')参数,读取后通过as_tibble()转换为tibble对象,但3列数据全部被识别为character类型,各列原始格式如下:- col_1:数值前带
/前缀,内容包含小数点 - col_2:百分比数值,以逗号作为小数分隔符,末尾带
%后缀 - col_3:普通数值,以逗号作为小数分隔符
- col_1:数值前带
- 转换目标:3列全部清洗为dbl(双精度数值)类型,规则为:
- col_1:移除开头的
/前缀与所有小数点 - col_2:将逗号替换为小数点,移除
%后缀 - col_3:将逗号替换为小数点
- col_1:移除开头的
实现代码
两种实现方式结果一致,可根据自己的代码习惯选择。
方法1:tidyverse链式写法(代码更简洁)
提前加载依赖包:
library(data.table) library(tibble) library(dplyr) library(stringr)
清洗转换逻辑:
# 代码中raw_tibble替换为你读取得到的字符型tibble对象名即可 clean_df <- raw_tibble %>% mutate( # 处理col_1:移除开头斜杠、移除所有小数点后转双精度 col_1 = str_remove(col_1, "^/") %>% str_remove_all("\\.") %>% as.double(), # 处理col_2:逗号替换为小数点、移除末尾百分号后转双精度 col_2 = str_replace(col_2, ",", "\\.") %>% str_remove("%$") %>% as.double(), # 处理col_3:逗号替换为小数点后转双精度 col_3 = str_replace(col_3, ",", "\\.") %>% as.double() )
补充说明:如果需要将col_2转为0-1区间的比例值(如12,34%转为0.1234),只需在col_2的处理链末尾加
%>%/(100)即可。
方法2:base R实现(无需额外加载字符串处理包)
clean_df <- raw_tibble # 处理col_1 clean_df$col_1 <- gsub("^/", "", clean_df$col_1) clean_df$col_1 <- gsub("\\.", "", clean_df$col_1) clean_df$col_1 <- as.double(clean_df$col_1) # 处理col_2 clean_df$col_2 <- gsub(",", ".", clean_df$col_2) clean_df$col_2 <- gsub("%$", "", clean_df$col_2) clean_df$col_2 <- as.double(clean_df$col_2) # 处理col_3 clean_df$col_3 <- gsub(",", ".", clean_df$col_3) clean_df$col_3 <- as.double(clean_df$col_3) # 转回tibble格式 clean_df <- as_tibble(clean_df)
结果校验
清洗完成后调用str(clean_df)查看列类型,三列均会显示为dbl类型,数值匹配预设转换规则。
内容的提问来源于stack exchange,提问作者user13117224
相关产品推荐
相关产品推荐

