Reputation: 31
I am fairly new to R programming and I apologize if this question has been answered already; I did search for an answer, but perhaps my wording is off.
I have imported a TXT file, performed my analysis and transformation of the data and now wish to write a CSV file for export. However, since this script is meant to run multiple files, I would like to use the file name from the input TXT file as the output CSV file.
>read.csv("C:\\Users\\Desktop\\filename.txt", header=FALSE)
>...
>...
>write.csv(Newfile, "filename.csv")
As an example, I want to be able to take the 'filename' portion of the pathway and (I would assume) create a string variable to pull into the name of the CSV file I want to write.
I know this is beginner level stuff, but any help would be appreciated. Thanks!
Upvotes: 3
Views: 5600
Reputation: 56249
We can keep the filename and path in a variable then manipulate to make output filename:
myInputFile <- "C:\\Users\\Desktop\\filename.txt"
myOutFile <- paste0(tools::file_path_sans_ext(myInputFile),".csv")
# test
myInputFile
# [1] "C:\\Users\\Desktop\\filename.txt"
myOutFile
# [1] "C:\\Users\\Desktop\\filename.csv"
Or more general approach, I use below to keep track of my ins and outs:
# define folders
folderWD <- "/users/myName/myXproject/"
folderInput <- paste0(folderWD, "data/")
folderOutput <- paste0(folderWD, "output/")
# input output files
fileInput <- paste0(folderInput, "filename.txt")
fileOutput <- paste0(folderOutput, tools::file_path_sans_ext(basename(fileInput)), ".csv")
# test
fileInput
# [1] "/users/myName/myXproject/data/filename.txt"
fileOutput
# [1] "/users/myName/myXproject/output/filename.csv"
#then codez
myInputData <- read.csv(fileInput, header = FALSE)
...
Newfile <- # do some stuff with myInputData
...
write.csv(Newfile, fileOutput)
Upvotes: 1