stata
stata

Reputation: 533

How to check file extensions in R

dset<-data.frame(x1=c(1,2),x2=c(3,4))

aaa<-function(data,fnm){
# if fnm have .txt extensions
if  {
write.table(data,fnm)
}
#   if fnm have .txt extensions,add .txt
else {
write.table(data,fnm)
}

}

aaa(data=dset,fnm=d:\\aaa)
aaa(data=dset,fnm=d:\\aaa.txt)

How to check file extensions in R? If the file has .txt extension then write, else add .txt then write.Thanks!

Upvotes: 1

Views: 3731

Answers (1)

lebatsnok
lebatsnok

Reputation: 6449

One way to check just for txt extension is:

grepl("\\.txt$", fnm)
# TRUE if the file name has txt extension

So the full code might be something like this:

fnm <- if(grepl("\\.txt$", fnm)) fnm else paste0(fnm, ".txt")
# adds ".txt" to `fnm` only if it's not already there

Upvotes: 5

Related Questions