如何从R中基本名称的结尾删除文件扩展名?



如何在文件夹中列出数据文件,并将其文件名(不带扩展名(作为数据帧中的因子存储?换句话说:如何从省略".csv"扩展名的文件名列表创建字符向量,并在从这些文件创建该数据帧后将此向量作为因子列表存储在数据帧中?

我的最终目标是将包含我的数据的文件名作为 StudyID 存储为数据帧中的因子。我认为这是一项非常简单的任务,但我还没有发现正则表达式所需的格式,或者 sapply 和 gsub 之间是否存在一些更改格式的交互。

两个文件夹"计划"和"模糊"分别包含名为 1.csv、2.csv 等的文件,有时带有非序列号。具体来说,我认为最好获得"模糊 1"、"计划1"、"模糊 2"、"计划2"等因素,以命名从这些文件导入的数据以引用研究 ID(编号(和类别(计划或模糊(。

我在 RStudio 1.0.143 中尝试过的代码,并附有关于发生的情况的评论:

# Create a vector of the files to process
filenames <- list.files(path = '../Desktop/data/',full.names=TRUE,recursive=TRUE) 
# We parse the path to find the terminating filename which contains the StudyID.
FileEndings <- basename(filenames)
# We store this filename as the StudyID
regmatches('.csv',FileEndings,invert=TRUE) -> StudyID   # Error: ‘x’ and ‘m’ must have the same length
lapply(FileEndings,grep('.csv',invert=TRUE)) -> StudyID # Error: argument "x" is missing, with no default
sapply(FileEndings,grep,'.csv',invert=TRUE) -> StudyID; StudyID # Wrong: Gives named integer vector of 1's
sapply(FileEndings,grep,'.csv',invert=TRUE,USE.NAMES=FALSE) -> StudyID; StudyID # Wrong: Gives integer vector of 1's
sapply(FileEndings,gsub,'.csv',ignore.case=TRUE,invert=TRUE,USE.NAMES=FALSE) -> StudyID; StudyID # Error: unused argument (invert = TRUE)
sapply(FileEndings,gsub,'.csv','',ignore.case=TRUE,USE.NAMES=FALSE) -> StudyID; StudyID # Wrong: vector of ""
sapply(FileEndings,gsub,'[:alnum:].csv','[:alnum:]',ignore.case=TRUE,USE.NAMES=FALSE) -> StudyID; StudyID # Wrong: vector of "[:alnum:]"
sapply(FileEndings,gsub,'[[:alnum:]].csv','[[:alnum:]]',ignore.case=TRUE,USE.NAMES=FALSE) -> StudyID; StudyID # Wrong: vector of "[[:alnum:]]"
sapply(FileEndings,gsub,'[:alnum:].csv','[:alnum:]',ignore.case=TRUE,USE.NAMES=FALSE) -> StudyID; StudyID # Error: '.' is an unrecognized escape

文档没有回答这个问题,多个在线网页提供了过于简单的例子,无法解决这个问题。我将继续搜索,但我希望您能提供解决方案来加快这项工作并帮助未来的用户。谢谢。

工具包中有一个内置函数:file_path_sans_ext.

我认为您错过了正则表达式中专门替换文件结尾的$。怎么样

gsub(filenames, pattern=".csv$", replacement="")

这应该会截断文件结尾。

如果你也想摆脱路径,那么你可以对路径进行类似的替换:

gsub(filenames, pattern="^.*AAPM2017//", replacement="")

如果你打算使用basename,你不妨从list.files中省略full.names参数(因为它是由 defualtFALSE的(。 我不完全清楚你的问题,但以下代码有帮助吗?

filenames <- list.files(path = 'DIRECTORY/',recursive=TRUE) 
csvfiles <- filenames[grep(".csv", filenames)] # grep to find pattern matches
finalnames <- sub("(.*)\.csv","",csvfiles) # sub to replace the pattern

最新更新