Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
101 views
in Technique[技术] by (71.8m points)

r - Splitting a file name into name,extension

I have the name of a file like this: name1.csv and I would like to extract two substrings of this string. One that stores the name1 in one variable and other that stores the extension, csv, without the dot in another variable.

I have been searching if there is a function like indexOf of Java that allows to do that kind of manipulation, but I have not found anything at all.

Any help?

question from:https://stackoverflow.com/questions/14173754/splitting-a-file-name-into-name-extension

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Use strsplit:

R> strsplit("name1.csv", "\.")[[1]]
[1] "name1" "csv"  
R> 

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> 

and

R> file_path_sans_ext("name1.csv")
[1] "name1"
R> 

as these are such a common tasks (cf basename in shell etc).


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...