如何在R中按数字升序读取tFileN.RAW格式的CSV文件
解决R中按数字升序读取tFileN.RAW文件的问题
当前list.files默认按字典序返回文件,导致tFile10.RAW排在tFile2.RAW前面,要实现按数字升序读取,需要提取文件名中的数字并以此排序,具体实现如下:
方法1:基础R实现(无需额外包)
# 获取所有RAW文件的完整路径 temp <- list.files(path = '/bigfolder/myname/smallfolder', pattern="RAW", full.names = TRUE) # 从文件名中提取数字部分,正则匹配tFile后的数字 file_nums <- as.integer(gsub(".*tFile(\\d+)\\.RAW", "\\1", temp)) # 按数字升序排序文件路径 sorted_temp <- temp[order(file_nums)] # 读取排序后的文件 final_list <- lapply(sorted_temp, read.csv)
方法2:用stringr包简化数字提取(需先安装包)
如果习惯用更简洁的字符串处理函数,可使用stringr包:
# 首次使用需安装包 # install.packages("stringr") library(stringr) temp <- list.files(path = '/bigfolder/myname/smallfolder', pattern="RAW", full.names = TRUE) # 提取tFile后的数字并转为整数 file_nums <- as.integer(str_extract(temp, "(?<=tFile)\\d+")) # 排序后读取文件 sorted_temp <- temp[order(file_nums)] final_list <- lapply(sorted_temp, read.csv)
处理完成后,final_list[[1]]对应tFile1.RAW,final_list[[2]]对应tFile2.RAW,完全按数字升序排列。
内容的提问来源于stack exchange,提问作者Programming Noob
相关产品推荐
相关产品推荐

