u
is the object that is stored the string text, is not the string itself. You can use paste
to compose the path name. Or better yet, as pointed out by @Rui-Arradas, file.path
:
file.path("C:/Users", u, "Database")
But if any user uses any different directory structure, the script will generate error. Can include the option for a different path to be passed as argument to Rscript, using the default path if none is provided:
# Captura argumentos da linha de comando
args <- commandArgs(trailingOnly = TRUE)
# Gera caminho padrão se nenhum for fornecido
if (!length(args)) {
wd <- file.path("C:/Users", Sys.info()["user"], "Database")
message("Caminho do Database não especificado. Usando ", wd)
} else {
wd <- args[1]
}
# Tenta estabelecer o diretório de trabalho; emite mensagem de erro se o caminho não existir
tryCatch(setwd(wd), error = function(...) message("Erro: Diretório não encontrado"))
Pass the directory name as argument to Rscript when needed:
Rscript script.R /caminho/do/diretorio
Windows / *Nix
On *Nix systems, til indicates the current user root. You can expand the conditional to create the path according to the system type:
if (!length(args)) {
if (.Platform$OS.type == "windows") {
wd <- file.path("C:/Users", Sys.info()["user"], "Database")
} else if (.Platform$OS.type == "unix") {
wd <- "~/Database"
} else {
stop("Indicar caminho do Database")
}
message("Caminho do Database não especificado. Usando ", wd)
} else {
wd <- args[1]
}
Only confirm if the value of .Platform$OS.type
is even "windows", not using Windows to be able to check.
Instead of
paste
,file.path("C:/Users", u, "Database")
is independent of the platform. + 1, by the way.– Rui Barradas
Thanks for the suggestion, I will update the reply. But platform independence is about using the backslash, not the users' directory structure. I had thought about using
path.expand("~")
, but I don’t know (nor can I verify) how consistent it behaves in Windows. As far as I have seen, you can direct to the user’s Documents folder depending on the configuration.– Carlos Eduardo Lagosta