简体   繁体   中英

File.choose() when outputting data?

I want to use the same script to process data in many text files that are stored in different places, and then to save the output to another unique location, without having to amend my script each time. I have input data using:

data <- read.table(file.choose(),header=T)

and would like to save the final table with a similar interface to select the location and enter a name for the file.

I have tried:

write.csv(data.table,file.choose())

but this only works if I create an empty .csv file with the name that I would like, in the location I would like before running the script.

Is there another (better) way of doing this?

There are a few possibilities:

library(gWidgets)
fileName <- gfile(type = "save") 

library(tcltk)
fileName <- tclvalue(tkgetSaveFile()) 

library(svDialogs)
fileName <- dlgSave()$res 

dlgSave asks for confirmation when it is needed to create a new file, tkgetSaveFile seems to be a bit more complicated for using additional arguments ( some basic examples ) and gfile offers a variety of options.

万一它被忽视了,file.choose() 还有一个内置参数,允许用户提供新的文件名:

fileName <- file.choose(new=TRUE)

If you are doing the same thing to your input files, I would use something like:

# input files from working directory
all.files <- list.files()

i <- 1
while (i <= length(all.files)){

data <- read.table(all.files[i],header=T)

# your script here

# output files
out.file <- paste(gsub(".csv","", all.files[i]),"_FINAL.csv",sep="")

write.csv(data,file=out.file)

i <- i+1
}

file.choose(new=TRUE) works for me.

Linux (Pop!_OS 20.04), RStudio 1.3.1073

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM