Reputation: 1335
I installed R and RStudio this week on a new Windows 10 machine. I want to use this R code to launch Excel and open a CSV file that is in a subdirectory of the current working directory:
file <- "example.csv"
sub_dir <- "subdirectory"
shell.exec(file.path(sub_dir, file))
But I get this error:
Error in shell.exec(file.path(sub_dir, file)) :
'subdirectory/example.csv' not found
However, if I provide shell.exec
with the full file path, this code works as expected:
shell.exec(file.path(getwd(), sub_dir, file))
The documentation for shell.exec
states:
The path in file is interpreted relative to the current working directory.
R versions 2.13.0 and earlier interpreted file relative to the R home directory, so a complete path was usually needed.
Why doesn't my original code (without getwd
) not work? Thanks.
Upvotes: 3
Views: 1509
Reputation: 1438
It looks to be related to the path separator in some wacky way. Below, I specify the the file path separator as \
and the command executes as expected. You could keep your call to file.path()
and simply wrap in normalizePath()
as another option.
file <- "example.csv"
sub_dir <- "subdirectory"
dir.create(sub_dir)
writeLines("myfile",file.path(sub_dir, file))
# Works
shell.exec(file.path(sub_dir, file, fsep = "\\"))
shell.exec(file.path(sub_dir, file))
#> Error in shell.exec(file.path(sub_dir, file)): 'subdirectory/example.csv' not found
Upvotes: 2