I have a script in R which returns a and I can print the result as
print(a)
Instead of print() I would like something like "speak()". So that the computer uses its "internal voice" and tells what the variable a is out loud.
Is this even possible in R?
(I use OSX)
(For example this "voice" can be heard in OSX when selecting a piece of text -> right-click -> speach -> begin speak.)
Problem solved!
As #Dason pointed out, it is possible to do a system call within R using system() and say as command.
The command in system() needs to be a complete string beginning with "say" and strings can be put together using sprintf().
Example:
a <- 2+5
b <- sprintf("say The result is %d", a)
system(b, intern = FALSE, ignore.stdout = FALSE, ignore.stderr =
FALSE, wait = TRUE, input = NULL)
Related
Python's argparse has a simple way to read parameters from a file:
https://docs.python.org/2/library/argparse.html#fromfile-prefix-chars
Instead of passing your arguments one by one:
python script.py --arg1 val1 --arg2 val2 ...
You can say:
python script.py #args.txt
and then the arguments are read from args.txt.
Is there a way to do this in ArgParse.jl?
P.S.: If there is no "default" way of doing this, maybe I can do it by hand, by calling parse_args on a list of arguments read from a file. I know how to do this in a dirty way, but it gets messy if I want to replicate the behavior of argparse in Python, where I can pass multiple files with #, as well as arguments in the command line, and then the value of a parameter is simply the last value passed to this parameter. What's the best way of doing this?
This feature is not currently present in ArgParse.jl, although it would not be difficult to add. I have prepared a pull request.
In the interim, the following code suffices for what you need:
# faithful reproduction of Python 3.5.1 argparse.py
# partial copyright Python Software Foundation
function read_args_from_files(arg_strings, prefixes)
new_arg_strings = AbstractString[]
for arg_string in arg_strings
if isempty(arg_string) || arg_string[1] ∉ prefixes
# for regular arguments, just add them back into the list
push!(new_arg_strings, arg_string)
else
# replace arguments referencing files with the file content
open(arg_string[2:end]) do args_file
arg_strings = AbstractString[]
for arg_line in readlines(args_file)
push!(arg_strings, rstrip(arg_line, '\n'))
end
arg_strings = read_args_from_files(arg_strings, prefixes)
append!(new_arg_strings, arg_strings)
end
end
end
# return the modified argument list
return new_arg_strings
end
# preprocess args, then parse as usual
ARGS = read_args_from_files(ARGS, ['#'])
args = parse_args(ARGS, s)
In a R session, I source a simple r script whose content is:
x = c(1,2)
x
as
source('my.r')
I wonder why running it in the R session doesn't show any output?
(I find that I can use print() to show the value of x.)
Thanks.
It is the way source is configured. You can change it with the options echo and print.eval:
echo logical; if TRUE, each expression is printed after parsing,
before evaluation.
print.eval logical; if TRUE, the result of
eval(i) is printed for each expression i; defaults to the value of
echo.
So try source("my.r", print.eval=TRUE)
So far as I understand it, when you run source, you are starting a separate environment inside which source is executing, just like any other function. As such, x "prints" the value of x inside that environment, but the console is one environment "up" the chain.
Try, for example,
foo<-function(x) {
x
return(4)
}
EDIT: James has more directly answered the "how" part of your question.
I want to use readLines function for input from console of variable number of lines and store it to a vector:
v <- readLines()
How do I signal the end of input? Control-c cancels the process and no 'v' object is formed. Control-Z stops R program altogether. Typing 'EOL' or 'EOF' do not work.
I tried following function but it gives error:
getinput = function(){
v=""
while(TRUE){
line = readLines(n=1)
if(line=="") break
v = v+line
}
v
}
> getinput()
firstentry
Error in v + line : non-numeric argument to binary operator
>
I am using R on Debian Linux. Thanks for your help.
<CTRL-D> will signal EOF. If you're using ess, try C-c C-c. Hope that helps and good luck. Leave a comment if you need further assistance.
Whether in a package or occasionally in base R, I sometimes want to add a little flavor to an existing function. Most of the times, this is a minor change of what should happen at the start or at the end of the function (silly example: I'd like the cat function to include a newline at the end by default).
Now I know I can simply overwrite an existing method by assigning my new implementation to its name, BUT: how, then, can I still use the old one? In the case of cat, I would have to do something like:
cat<-function(... , file = "", sep = " ", fill = FALSE, labels = NULL,
append = FALSE)
{
cat(..., "\n" , file = file, sep = sep, fill = fill, labels = labels,
append = append)
}
This means using the 'old' cat in the implementation of the new one. Now if I understand anything about how calling and late binding in R work, this will simply fail (infinite recursion).
So is there a way of achieving this (in the spirit of object-oriented overrides of functions), without resorting to
giving my new function another name (I want it to 'just work')
saving the old function under some other name (Then, when I create
this function in another R session, I might forget the extra step)
using all the source of the original function (As #Andrie said: it is important to have the most elegant solution possible)
Is there a paradigm for this? Or how could I go about this in the safest way possible? Or am I just wishing for too much?
Edit Given #Andrie's answer: this can be done quite simply. However, Andrie's trick will not work if I want to alter the behaviour of some function in a package that is called by another function in the package.
As an example: I have made numerous additions to the plotting functions of the glmnet package. But if you look at plot.cv.glmnet and the likes, you will see that they forward the call to another function within that package, so I'd really need to inject my new version into the package (which, by the way, can be done with reassignInPackage). But then of course the namespace prefixing will fail because I've just replaced the namespaced version. This example is not as contrived as it might seem: I've been there quite a few times. On the other hand, maybe somebody will/can argue that I should drop my requirements in that case? Which would be the best way to go then?
If I understand you correctly, I think it's a simple matter of referring to namespace::function, i.e. in this case use base::cat inside your function.
For example:
cat <- function(... , file = "", sep = " ", fill = FALSE, labels = NULL,
append = FALSE)
{
base::cat(..., "\n" , file = file, sep = sep, fill = fill, labels = labels,
append = append)
}
> cat("Hello", "world!")
Hello world!
> cat("Text on line 2")
Text on line 2
How do you print to stderr in R?
This would especially useful for scripts written in Rscript.
Actually the following works for me:
write("prints to stderr", stderr())
write("prints to stdout", stdout())
Here's a more flexible version for debugging/verbose use in Rscript. Not only it prints to stderr as you ask, but it also allows you to pass variable number of arguments, types etc, like printf does.
v <- function(...) cat(sprintf(...), sep='', file=stderr())
Now you can do things like:
v("name: %s age: %d\n", name, age)
etc.
message('for writing diagnostic info to standard error')
message is used for generating ‘simple’ diagnostic messages which are neither warnings nor errors, but nevertheless represented as conditions. Unlike warnings and errors, a final newline is regarded as part of the message, and is optional. The default handler sends the message to the stderr() connection.
Is it possible to configure the print
function to print to stderr?
From Ripley himself:
No, but where standard output goes is
controlled by sink(), so you can
achieve the same effect. R internally
has no idea what output comes from
print() (which is not just one
function but hundreds of methods).
Contrary to the accepted answer's suggestion to use the write() function, this would be an inappropriate use of the function as it is designed to be used for writing data to a file instead of messages. From the write() documentation, we have:
The data (usually a matrix) x are written to file file. If x is a two-dimensional matrix you need to transpose it to get the columns in file the same as those in the internal representation.
Moreover, note that write() provides a convenience wrapper for data output of columns.
write
# function (x, file = "data", ncolumns = if (is.character(x)) 1 else 5,
# append = FALSE, sep = " ")
# cat(x, file = file, sep = c(rep.int(sep, ncolumns - 1), "\n"),
# append = append)
That said, I would recommend using cat() alongside of the appropriate condition handler stderr() or stdout() in file = ... parameter.
Thus, to write a message to standard error, one should use:
cat("a message that goes to standard error", file = stderr())
Or:
message("also sent to standard error")
For standard out, just use cat() directly as it is setup to write to stdout() by default.
cat("displays in standard out by default")