How do you print to stderr in R? - r

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")

Related

When defined in a script, Julia functions don't print output

I have this Julia script:
function f(x,y)
x+y
end
f(3, 4)
When I run this in the live terminal (via copy/paste), I get the desired result 7. But if I run the script, the output from the function is suppressed. Why is that?
Julia, unlike Matlab, doesn't automatically print values (the REPL does since that's what it's for: REPL = "read, eval, print loop"). You have to explicitly print the value using print or show, e.g. show(f(3, 4)). In this case, print and show do the same thing, but in general they have somewhat different meanings:
print([io::IO], xs...)
Write to io (or to the default output stream stdout if io is not given) a canonical (un-decorated) text representation. The representation used by print includes minimal formatting and tries to avoid Julia-specific details.
versus
show(x)
Write an informative text representation of a value to the current output stream. New types should overload show(io::IO, x) where the first argument is a stream. The representation used by show generally includes Julia-specific formatting and type information.
Note that there is also the #show macro, which prints the expression that is evaluated followed by its value, like so:
julia> #show f(3, 4);
f(3, 4) = 7

How to program the computer to speak put loud in R

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)

Parameter file in ArgParse.jl?

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)

Why does sourcing a script not print out to stdout?

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.

Getting objects in a situation where their name matters

I have a list of functions that I'd like to make documentation for. My question is not about how to do this, but it provides a convenient example of something I'm curious about.
prompt takes a function and a character string as arguments, and writes a help file on that function to the file represented by the character string path. In looping over the files, using prompt(f,filename=...) doesn't work since f is of type character. I tried get(f), which pulls the function out just fine, but doesn't give prompt enough information to work with (see below). So how do I force a character element to return the whole object not just the function that it names?
files <- c("current.market","current.portfolio.bond","fund","genAccount","genHistory.market","history.market","maRketSim.version","summary.vasicek.discrete","vasicek.discrete")
for(f in files) {
prompt( get(f), filename=paste("c:/myproject/man/",f,".Rd",sep="") )
}
Error in prompt.default(get(f), filename = paste("F:/Documents/R-projects/maRketSim/man/", :
cannot determine a usable name
?prompt tells us that
Arguments:
object: an R object, typically a function for the default method.
Can be ‘missing’ when ‘name’ is specified.
So I think prompt() already does what you want:
> prompt(name = "print", filename = "print.Rd")
Created file named 'print.Rd'.
Edit the file and move it to the appropriate directory.
Which does produce the relevant Rd file:
> writeLines(readLines("~/print.Rd"))
\name{print}
\alias{print}
%- Also NEED an '\alias' for EACH other topic documented here.
\title{
%% ~~function to do ... ~~
}
\description{
%% ~~ A concise (1-5 lines) description of what the function does. ~~
}
\usage{
print(x, ...)
}
%- maybe also 'usage' for other objects documented here.
\arguments{
\item{x}{
%% ~~Describe \code{x} here~~
....
I should add, that get("foo") does return the actual function, it is just the way that prompt() is coded that it can't work with an anonymous function as returned by get().

Resources