When I want to load a file into R, what would be a way to do so programmatically (or semi programmatically) instead of just manually copy paste the path and switch \ to / so R could read it (because \ is an escape character in R)
One method mentioned by #Roland is using scan
list.files(scan(file=file(description = "clipboard"), what = "character", allowEscapes = FALSE))
Which will need modifications if the path contains a space like
"C:\Users\David Arenburg\"
normalizepath maybe what you are looking for:
> normalizePath(c(R.home(), tempdir()))
[1] "C:\\Program Files\\R\\R-3.1.0"
[2] "C:\\Users\\john\\AppData\\Local\\Temp\\RtmpysKuFi"
> normalizePath(c(R.home(), tempdir()), winslash = '/')
[1] "C:/Program Files/R/R-3.1.0"
[2] "C:/Users/john/AppData/Local/Temp/RtmpysKuFi"
Use readClipboard if you are on windows and have problems copying and pasting filepaths. For example I copy a file path from a windows folder so it is on the clip board then I can use:
> readClipboard()
[1] "C:\\Users\\john\\AppData\\Local\\Temp"
You can then use `normalizePath to correct the windows flavour of paths.
Perhaps use choose.files() to pick the file followed by normalizePath() if you want to convert its path name to R's forward slashes.
Related
A combination of frustrating problems here.
Essentially I want R to open an external program with command line parameters. I am currently trying to achieve it on a Windows machine, ideally it would work cross-platform.
The program (chimera.exe) is in a directory containing spaces: C:\Program Files\Chimera1.15\bin\
The command line options could be for instance a --nogui flag and a script name, so from the shell I would write (space-specifics aside):
C:\Program Files\Chimera1.15\bin\chimera.exe --nogui scriptfile
This works if I go in windows cmd.exe to the directory itself and just type chimera.exe --nogui scriptfile
Now in R:
I've been playing with shell(), shell.exec(), and system(), but essentially I fail because of the spaces and/or the path separators.
most of the times system() just prints "127" for whatever reason:
> system("C:/Program Files/Chimera1.15/bin/chimera.exe")
[1] 127`
back/forward slashes complicate the matter further but don't make it work:
> system("C:\Program Files\Chimera1.15\bin\chimera.exe")
Error: '\P' is an unrecognized escape in character string starting "C\P"
> system("C:\\Program Files\\Chimera1.15\\bin\\chimera.exe")
[1] 127
> system("C:\\Program\ Files\\Chimera1.15\\bin\\chimera.exe")
[1] 127
> system("C:\\Program\\ Files\\Chimera1.15\\bin\\chimera.exe")
[1] 127
When I install the program in a directory without spaces, it works. How can I escape or pass on the space in system() or related commands or how do I invoke the program otherwise?
Try system2 as it does not use the cmd line processor and use r"{...}" to avoid having to double backslashes. This assumes R 4.0 or later. See ?Quotes for the full definition of the quotes syntax.
chimera <- r"{C:\Program Files\Chimera1.15\bin\chimera.exe}"
system2(chimera, c("--nogui", "myscript"))
For example, this works for me (you might need to change the path):
R <- r"{C:\Program Files\R\R-4.1\bin\x64\Rgui.exe}" # modify as needed
system2(R, c("abc", "def"))
and when Rgui is launched we can verify that the arguments were passed by running this in the new instance of R:
commandArgs()
## [1] "C:\\PROGRA~1\\R\\R-4.1\\bin\\x64\\Rgui.exe"
## [2] "abc"
## [3] "def"
system
Alternately use system but put quotes around the path so that cmd interprets it correctly -- if it were typed into the Windows cmd line the quotes would be needed too.
system(r"{"C:\Program Files\Chimera1.15\bin\chimera.exe" --nogui myscript}")
I wish to call an executable file from Julia via Base.run (documented here) and pass command line options to that executable, but I can't figure out how to do that. In my specific example the executable is Notepad++ and the command line options are
-alwaysOnTop -nosession
This example code works, but doesn't pass the command line options:
function open_file_in_notepadpp()
exepath = "C:/Program Files (x86)/notepad++/notepad++.exe" #Default location on 64 bit Windows
command_line_options = "-alwaysOnTop -nosession "
filetoopen = "c:/temp/foo.txt"
Base.run(`$exepath $filetoopen`, wait = false)
end
I've tried incorporating command_line_options a fair number of ways using backticks, double quotes etc. to no avail, so for example neither of the lines below work:
Base.run(`$exepath $filetoopen`, `$command_line_options`,wait = false)
Base.run(`$exepath $command_line_options $filetoopen`,wait = false)
In the Windows Command Prompt the following works correctly:
"C:/Program Files (x86)/notepad++/notepad++.exe" -alwaysOnTop -nosession "c:/temp/foo.txt"
Could someone explain what I'm missing?
If you substitute a string that contains spaces to a command it will get quoted. Hence, your command line arguments will be quoted and you get
julia> `$exepath $filetoopen $command_line_options`
`'C:/Program Files (x86)/notepad++/notepad++.exe' c:/temp/foo.txt '-alwaysOnTop -nosession '`
I guess what you really need is
julia> command_line_options = ["-alwaysOnTop", "-nosession"]
2-element Array{String,1}:
"-alwaysOnTop"
"-nosession"
julia> `$exepath $filetoopen $command_line_options`
`'C:/Program Files (x86)/notepad++/notepad++.exe' c:/temp/foo.txt -alwaysOnTop -nosession`
Running the latter with run should work. Unfortunately I can't test it on my machine.
crstnbr's answer was correct, but he was unable to test on his machine. Here is the corrected code:
function open_file_in_notepadpp()
exepath = "C:/Program Files (x86)/notepad++/notepad++.exe" #Location if one follows the defaults in the notepad++ installer on 64 bit Wndows
command_line_options = ["-alwaysOnTop", "-nosession"] #Use an array to prevent the options being quoted
filetoopen = "c:/temp/foo.txt"
Base.run(`$exepath $filetoopen $command_line_options`,wait = false)
end
I want to read in a file with fread in R. I have 7z installed.
I tried
fread(shell(cmd = '7z l test.txt.gz'), shell = 'cmd.exe'))
However I get the error
Error in fread(shell(cmd = paste0("7z x ", "\"", dest, "\""), shell = "cmd.exe")) :
'input' must be a single character string containing a file name, a command, full path to a file, a URL starting 'http[s]://', 'ftp[s]://' or 'file://', or the input data itself
I'm looking for something similar to:
fread(shell(cmd = 'unzip -cq test.zip', shell = 'cmd.exe'))
One work-around is to copy 7z.exe to the project folder. And try:
DT = fread(cmd = '7z e -so "test.zip"')
Some people suggested adding 7-zip to Windows PATH Environment Variable. But it did not work for me.
I have an R script that takes a file as input, and I want a general way to know whether the input is a file that exists, and is not a directory.
In Python you would do it this way: How do I check whether a file exists using Python?, but I was struggling to find anything similar in R.
What I'd like is something like below, assuming that the file.txt actually exists:
input.good = "~/directory/file.txt"
input.bad = "~/directory/"
is.file(input.good) # should return TRUE
is.file(input.bad) #should return FALSE
R has something called file.exists(), but this doesn't distinguish files from directories.
There is a dir.exists function in all recent versions of R.
file.exists(f) && !dir.exists(f)
The solution is to use file_test()
This gives shell-style file tests, and can distinguish files from folders.
E.g.
input.good = "~/directory/file.txt"
input.bad = "~/directory/"
file_test("-f", input.good) # returns TRUE
file_test("-f", input.bad) #returns FALSE
From the manual:
Usage
file_test(op, x, y) Arguments
op a character string specifying the test to be performed. Unary
tests (only x is used) are "-f" (existence and not being a directory),
"-d" (existence and directory) and "-x" (executable as a file or
searchable as a directory). Binary tests are "-nt" (strictly newer
than, using the modification dates) and "-ot" (strictly older than):
in both cases the test is false unless both files exist.
x, y character vectors giving file paths.
You can also use is_file(path) from the fs package.
I wish to get the fully qualified name of a file in R, given any of the standard notations. For example:
file.ext
~/file.ext (this case can be handled by path.expand)
../current_dir/file.ext
etc.
By fully qualified file name I mean, for example, (on a Unix-like system):
/home/user/some/path/file.ext
(Edited - use file.path and attempt Windows support) A crude implementation might be:
path.qualify <- function(path) {
path <- path.expand(path)
if(!grepl("^/|([A-Z|a-z]:)", path)) path <- file.path(getwd(),path)
path
}
However, I'd ideally like something cross-platform that can handle relative paths with ../, symlinks etc. An R-only solution would be preferred (rather than shell scripting or similar), but I can't find any straightforward way of doing this, short of coding it "from scratch".
Any ideas?
I think you want normalizePath():
> setwd("~/tmp/bar")
> normalizePath("../tmp.R")
[1] "/home/gavin/tmp/tmp.R"
> normalizePath("~/tmp/tmp.R")
[1] "/home/gavin/tmp/tmp.R"
> normalizePath("./foo.R")
[1] "/home/gavin/tmp/bar/foo.R"
For Windows, there is argument winslash which you might want to set all the time as it is ignored on anything other than Windows so won't affect other OSes:
> normalizePath("./foo.R", winslash="\\")
[1] "/home/gavin/tmp/bar/foo.R"
(You need to escape the \ hence the \\) or
> normalizePath("./foo.R", winslash="/")
[1] "/home/gavin/tmp/bar/foo.R"
depending on how you want the path presented/used. The former is the default ("\\") so you could stick with that if it suffices, without needing to set anything explicitly.
On R 2.13.0 then the "~/file.ext" bit also works (see comments):
> normalizePath("~/foo.R")
[1] "/home/gavin/foo.R"
I think I kind of miss the point of your question, but hopefully my answer can point you into the direction you want (it integrates your idea of using paste and getwdwith list.files):
paste(getwd(),substr(list.files(full.names = TRUE), 2,1000), sep ="")
Edit: Works on windows in some tested folders.