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

How to delete file extension from ending of basename in R?

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

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

两个文件夹 'planned' 和 'blurred' 分别包含名为 1.csv、2.csv 等的文件,有时带有非序号。具体来说,我觉得最好获取因子"Blurred 1"、"Planned 1"、"Blurred 2"、"Planned 2"等来命名从这些文件中导入的数据,以供参考Study 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

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

如果您打算使用 basename,您不妨省略 list.files 中的 full.names 参数(默认情况下为 FALSE)。 我不是很清楚你的问题,但下面的代码有帮助吗?

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

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

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

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

这应该截断文件结尾。

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

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