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)
Related
The result variable is a json-type string, which is very long. What is the option in Julia REPL that allows only a limited output when the variable is this long? DataFrame is originally only partially output. I hope that the general variables will also be output like that.
You can overwrite the display method for AbstractStrings:
import Main.display
display(x::AbstractString) =
show(length(x)<=50 ? x : SubString(x,1,50)*"…")
Let us test it:
julia> str = join(rand('a':'z', 200))
"wcbifwzglgqyenrcdgdxagohlwdoxrrumoaltklkjauptwzrmi…"
Is there a way to call a function when the name of the function is decided at the runtime? For example, calling pdf would look like:
pdf("myfile.pdf")
but is there a way, I could do something like:
media_type = "pdf"
media_type("myfile.pdf")
1) do.call Use do.call
do.call(media_type, list("myfile.pdf"))
2) match.fun Another approach is match.fun
fun <- match.fun(media_type)
fun("myfile.pdf")
3) switch Another approach is the following where an argument to switch would be added for each media type. stop is the default. It generates an error when called.
fun <- switch(media_type, pdf = pdf, stop)
fun("myfile.pdf")
4) eval/call This also works although the use of eval is generally frowned upon:
eval(call(media_type, "myfile.pdf"))
I'm not sure if this is what you're wanting, but given the example in your question, it is possible. Assuming you have code that determines which function you want to call, you can use do.call to pass in the string based function name. I had to wrap the input in a list to make it happy, but that's not a big deal most of the time.
f = "mean"
d = c(1,2,3)
do.call(f,list(d))
#> 2
I was going through swirl() again as a refresher, and I've noticed that the author of swirl says the command ?matrix is the correct form to calling for a help screen. But, when I run ?matrix(), it still works? Is there a difference between having and not having a pair of parenthesis?
It's not specific to the swirl environment (about which I was entirely unaware until 5 minutes ago) That is standard for R. The help page for the ? shortcut says:
Arguments
topic
Usually, a name or character string specifying the topic for which help is sought.
Alternatively, a function call to ask for documentation on a corresponding S4 method: see the section on S4 method documentation. The calls pkg::topic and pkg:::topic are treated specially, and look for help on topic in package pkg.
It something like the second option that is being invoked with the command:
?matrix()
Since ?? is actually a different shortcut one needs to use this code to bring up that page, just as one needs to use quoted strings for help with for, if, next or any of the other reserved words in R:
?'?' # See ?Reserved
This is not based on a "fuzzy logic" search in hte help system. Using help instead of ? gets a different response:
> help("str()")
No documentation for ‘str()’ in specified packages and libraries:
you could try ‘??str()’
You can see the full code for the ? function by typing ? at the command line, but I am just showing how it starts the language level processing of the expressions given to it:
`?`
function (e1, e2)
{
if (missing(e2)) {
type <- NULL
topicExpr <- substitute(e1)
}
#further output omitted
By running matrix and in general any_function you get the source code of it.
Can you write a function that prints out its own name?
(without hard-coding it in, obviously)
You sure can.
fun <- function(x, y, z) deparse(match.call()[[1]])
fun(1,2,3)
# [1] "fun"
You can, but just in case it's because you want to call the function recursively see ?Recall which is robust to name changes and avoids the need to otherwise process to get the name.
Recall package:base R Documentation
Recursive Calling
Description:
‘Recall’ is used as a placeholder for the name of the function in
which it is called. It allows the definition of recursive
functions which still work after being renamed, see example below.
As you've seen in the other great answers here, the answer seems to be "yes"...
However, the correct answer is actually "yes, but not always". What you can get is actually the name (or expression!) that was used to call the function.
First, using sys.call is probably the most direct way of finding the name, but then you need to coerce it into a string. deparse is more robust for that.
myfunc <- function(x, y=42) deparse(sys.call()[[1]])
myfunc (3) # "myfunc"
...but you can call a function in many ways:
lapply(1:2, myfunc) # "FUN"
Map(myfunc, 1:2) # (the whole function definition!)
x<-myfunc; x(3) # "x"
get("myfunc")(3) # "get(\"myfunc\")"
The basic issue is that a function doesn't have a name - it's just that you typically assign the function to a variable name. Not that you have to - you can have anonymous functions - or assign many variable names to the same function (the x case above).
I'd like to give a params argument to a function and then attach it so that I can use a instead of params$a everytime I refer to the list element a.
run.simulation<-function(model,params){
attach(params)
#
# Use elements of params as parameters in a simulation
detach(params)
}
Is there a problem with this? If I have defined a global variable named c and have also defined an element named c of the list "params" , whose value would be used after the attach command?
Noah has already pointed out that using attach is a bad idea, even though you see it in some examples and books. There is a way around. You can use "local attach" that's called with. In Noah's dummy example, this would look like
with(params, print(a))
which will yield identical result, but is tidier.
Another possibility is:
run.simulation <- function(model, params){
# Assume params is a list of parameters from
# "params <- list(name1=value1, name2=value2, etc.)"
for (v in 1:length(params)) assign(names(params)[v], params[[v]])
# Use elements of params as parameters in a simulation
}
Easiest way to solve scope problems like this is usually to try something simple out:
a = 1
params = c()
params$a = 2
myfun <- function(params) {
attach(params)
print(a)
detach(params)
}
myfun(params)
The following object(s) are masked _by_ .GlobalEnv:
a
# [1] 1
As you can see, R is picking up the global attribute a here.
It's almost always a good idea to avoid using attach and detach wherever possible -- scope ends up being tricky to handle (incidentally, it's also best to avoid naming variables c -- R will often figure out what you're referring to, but there are so many other letters out there, why risk it?). In addition, I find code using attach/detach almost impossible to decipher.
Jean-Luc's answer helped me immensely for a case that I had a data.frame Dat instead of the list as specified in the OP:
for (v in 1:ncol(Dat)) assign(names(Dat)[v], Dat[,v])