Вы можете обменять отсутствующее условие () на следующее:
if (working.dir=="") {
print ("Working directory not specified! Will use present working directory.")
working.dir <- as.character(file.path(getwd()))
} else {
print ("Working directory is specified!")
working.dir <- working.dir
}
И изменить аргумент для working_dir
на ( default = "" ):
parser$add_argument(
"--working_dir",
dest = "working.dir",
type = "character",
metavar = "DIR",
default="",
required = FALSE,
help = "Working directory where files are present"
)
И измените tryCatch
на:
tryCatch(merge_em(x, y, working.dir), finally = print("Fin"))
Почему вы используете setwd () для части finally?Если аргумент не указан, нечего задавать или?
Например, вы можете вызвать скрипт следующим образом, например:
Rscript merge_em.r data_frame1, data_frame2
Или с каталогом:
Rscript merge_em.r data_frame1, data_frame2, --working_dir "path_to_folder"
Полный код:
library(argparse)
merge_em <- function (x, y, working.dir){
mergedfile <- merge (x, y, by = intersect(names(x), names(y)))
if (working.dir=="") {
print ("Working directory not specified! Will use present working directory.")
working.dir <- as.character(file.path(getwd()))
} else {
print ("Working directory is specified!")
working.dir <- working.dir
}
setwd(working.dir)
write.csv(x = mergedfile, file = "merged.txt",
row.names = FALSE,
quote = FALSE
)
}
main <- function() {
# breaks if you set warn = 2
options(error = traceback,
warn = 1)
parser <- ArgumentParser(prog = "merge_em.r",
description = "Merge dataframes")
parser <- ArgumentParser()
parser$add_argument("x")
parser$add_argument("y")
parser$add_argument(
"--working_dir",
dest = "working.dir",
type = "character",
metavar = "DIR",
default="",
required = FALSE,
help = "Working directory where files are present"
)
args <- parser$parse_args()
working.dir <- args$working.dir
x <- args$x
if (!R.utils::isAbsolutePath(x))
x <- file.path(working.dir, x)
y <- args$y
if (!R.utils::isAbsolutePath(y))
y <- file.path(working.dir, y)
tryCatch(merge_em(x, y, working.dir), finally = print("Fin"))
}
main()