Pass file name to perl from R - r

I want to pass file name to perl from R. For example, this system command from R to execute perl works well
system("perl file.pl name.txt")
name.txt is already existing in the R working directory. Now,
a<-"name.txt"
how to pass this to perl?

If I understand correctly I think this may work:
a <- "name.txt"
system(sprintf("perl file.pl %s", a))

Tyler's method works, but there is also this way:
a <- "name.txt"
system(paste("perl file.pl", a))
Depending on the situation, one may be more intuitive over the other.

Related

passing variable in r system command

I am trying to pass variable as an argument to system command in R.
> system("ls>abc.csv") #this works
> k<-"abc.csv"
> system("ls>k") #this does not work
> system2("ls>k") #this does not work
sh: ls>k: command not found
> system("ls>$k") #this does not work
sh: $k: ambiguous redirect
You can use paste to build the OS command and pass to system
system(paste("ls >", k))
The problem here is that R does not recognize variable k if you put it in a string.
But indeed it is very useful to put the file name in a variable if you want to use it again and again.
Can you try
system(paste0("ls>", k))
If this works, you can also write a small function:
"%&%" <- function(a, b)paste0(a, b)
And then you can do
system("ls>"%&%k)

how to print the passed argument variable in R

I want to print every argument passed to function read.table. My idea was to write some decorator that is easy in Python. But for R, I don't know how to do it, what I learned was to use trace(). However, I don't know how to print variables inside trace.
Example:
trace(f)
a <- "123"
f(a)
untrace(f)
trace() will only output f(a), but I want to know the evaluation of a.
thanks for your guys' help, I find the answer.
Simply use the following code:
trace(f, tracer = quote(print(lapply(as.list(match.call()),eval))))
d<-1
f(d)
untrace(f)

Run Rscript.exe on batch file with optional arguments

I run a Windows batchfile (.bat)
path_to_Rscript.exe file.R parameter1 parameter2 parameter3
on a file called file.R
In file.R, I read the arguments using
commandArgs(trailingOnly = TRUE)
ABC <- args[1]
DEF <- args[2]
GHI <- args[3]
In case there is no parameter2, calling only
path_to_Rscript.exe file.R parameter1 parameter3
how can I make sure that parameter3 is not assigned to DEF?
So far, I used %% as a placeholder, but I am not sure whether this is a common approach.
Is there a general placeholder for empty parameters?
There is no general "no arg" placeholder, it depends on the progam.
The answer is that you can't make sure p3 is not assigned to DEF without some assumptions, i.e., if you only have two arguments then they are always going to be ABC and GHI. In that case, you check for the length of commandArgs and adjust accordingly - that is a very narrow solution.
If you want to use optional positional arguments (which is generally a bad idea), they'd have to be at the end and then you really only get one for the same reason your facing now.
The best way out of this conundrum is to use docopt. If you can't use docopt, then your stuck implementing pieces of a command-line parser which is a generally solved problem.

Can't add constant to vector in R

I don't know what is happening, but I can't seem to add a constant to a vector. For example, typing in the console c(1,2,3,4)+5 returns 15 instead of (6,7,8,9). What am I doing wrong?
Thank you for your help.
Someone.... probably you ... has redefined the "+" function. It's easy to do:
> `+` <- function(x,y) sum(x,y)
> c(1,2,3,4)+5
[1] 15
It's easy to fix, Just use rm():
> rm(`+`)
> c(1,2,3,4)+5
[1] 6 7 8 9
EDIT: The comments (which raised the alternate possibility that c had instead been redefined as sum) are prompting me to add information about how to examine and recover from the alternative possibilities. You could use two methods to determine which of the two functions in the expression c(1,2,3,4) + 5 was the culprit. One could either type their names (with the backticks enclosing +), and note whether you got the proper definition:
> `+`
function (e1, e2) .Primitive("+")
> c
function (..., recursive = FALSE) .Primitive("c")
Using rm on the culprit (the on that doesn't match above) remains the quickest solution. Using a global rm is an in-session brainwipe:
rm(list=ls())
# all user defined objects, including user-defined functions will be removed
The advice to quit and restart would not work in some situations. If you quit-with-save, the current function definitions would be preserved. If you had earlier quit-with-save from a session where the redefinition occurred, then not saving in this session would not have fixed the problem, either. The results of prior session are held in a file named ".Rdata and this file is invisible for both Mac and Windows users because the OS file viewer (Mac's Finder.app or MS's Windows Explorer) will not display file names that begin with a "dot". I suspect that Linux users get to see them by default since using ls in a Terminal session will show them. (It's easy to find ways to change that behavior in a Mac, and that is the way I run my device.) Deleting the .Rdata file is helpful in this instance, as well as in the situation where your R session crashes on startup.

Verbatim command arguments: deparse(substitute(foo)) in a wrapper

Here's a little puzzler for those fluent in the nitty-gritty of how the R evaluator handles function calls. Suppose I wanted to write a function that takes an R statement, same as what I'd write at the command line, and echoes both it, and the evaluated result. Example:
> p.eval(sum(1:3))
sum(1:3) --> 6
That's easy; here's the definition of p.eval():
p.eval <- function(v,prefix="--> ") {
cmd <- deparse(substitute(v)); cat(cmd,prefix,v,"\n")
}
But suppose I now want to write a wrapper around p.eval, to be invoked the same way; perhaps as a somewhat demented binary operator with a dummy second argument:
%PE% <- function(x,...) p.eval(x)
I'd like to invoke it like so: sum(1:3) %PE% 0 should be equivalent to the old p.eval(sum(1:3)). This doesn't work, of course, because the deparse(substitute()) of p.eval() now gives x.
Question to the enlightened: is there a way to make this work as I desire?.. For this particular usage, I'm quite fine with defining %PE% by copying/pasting the one-liner definition of p.eval, so this question is mostly academic in nature. Maybe I'll learn something about the nitty-gritty of the R evaluator :)
P.S.: Why might one find the above functions useful?.. Suppose I develop some analysis code and invoke it non-interactively through org-babel (which is most definitely worth playing with if you are an Org-mode and/or an Emacs user). By default, org-babel slurps up the output as things are evaluated in the interpreter. Thus, if I want to get anything but raw numbers, I have to explicitly construct strings to be printed through cat or paste, but who wants to do that when they are flying through the analysis?.. The hack above allows you to simply append %PE%0 after a line that you want printed, and this echoes the command to the org output.
Try this:
> "%PE%" <- function(x, ...) do.call(p.eval, list(substitute(x)))
> sum(1:3) %PE% 0
sum(1:3) --> 6
Also could just have p.eval return "v" and then:
p.eval <- function(v,prefix="--> ") {
cmd <- deparse(substitute(v)); cat(cmd,prefix,v,"\n") ; return(v) }
"%PE%" <- function(x, y=NULL) x
sum(1:3) %PE% Inf
#[1] 6
sum(1:3) %PE% # won't accept single argument
r # give it anything
#[1] 6

Resources