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

DBi*_*nJP 1 regex csv r filepath gsub

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

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

'planned' 和 'blurred' 两个文件夹分别包含名为 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
Run Code Online (Sandbox Code Playgroud)

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

Hon*_*Ooi 5

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