更新时间:2022-06-01 02:30:23
使用strsplit
:
R> strsplit("name1.csv", "\.")[[1]]
[1] "name1" "csv"
R>
请注意,您 a) 需要对点进行转义(因为它是正则表达式的元字符)并且 b) 处理 strsplit()
返回一个通常只有第一个列表的事实元素很有趣.
Note that you a) need to escape the dot (as it is a metacharacter for regular expressions) and b) deal with the fact that strsplit()
returns a list of which typically only the first element is of interest.
更通用的解决方案涉及正则表达式,您可以在其中提取匹配项.
A more general solution involves regular expressions where you can extract the matches.
对于文件名的特殊情况,您还有:
For the special case of filenames you also have:
R> library(tools) # unless already loaded, comes with base R
R> file_ext("name1.csv")
[1] "csv"
R>
和
R> file_path_sans_ext("name1.csv")
[1] "name1"
R>
因为这些是很常见的任务(参见 shell 中的 basename
等).
as these are such a common tasks (cf basename
in shell etc).