Given the name of an R object (as a string), how can I return the object with that name?
(The context in which this comes up is that I am running the function findGlobals, which returns a vector objects as a strings. I would like to then iterate through the list and test to make sure each name refers to a function using is.function. If you know of a solution to this specific problem without the more general question above, that would also be appreciated.)
get() is what you're looking for. And by "iterate" I assume you mean using an apply variant, e.g.
sapply(ls(), FUN = function(x) is.function(get(x)))
Related
Help files call attributes() a function. Its syntax looks like a function call. Even class(attributes) calls it a function.
But I see I can assign something to attributes(myobject), which seems unusual. For example, I cannot assign anything to log(myobject).
So what is the proper name for "functions" like attributes()? Are there any other examples of it? How do you tell them apart from regular functions? (Other than trying supposedfunction(x)<-0, that is.)
Finally, I guess attributes() implementation overrides the assignment operator, in order to become a destination for assignments. Am I right? Is there any usable guide on how to do it?
Very good observation Indeed. It's an example of replacement function, if you see closely and type apropos('attributes') in your R console, It will return
"attributes"
"attributes<-"
along with other outputs.
So, basically the place where you are able to assign on the left sign of assignment operator, you are not calling attributes, you are actually calling attributes<- , There are many functions in R like that for example: names(), colnames(), length() etc. In your example log doesn't have any replacement counterpart hence it doesn't work the way you anticipated.
Definiton(from advanced R book link given below):
Replacement functions act like they modify their arguments in place,
and have the special name xxx<-. They typically have two arguments (x
and value), although they can have more, and they must return the
modified object
If you want to see the list of these functions you can do :
apropos('<-$') and you can check out similar functions, which has similar kind of properties.
You can read about it here and here
I am hopeful that this solves your problem.
How do I remove an object from the current function environment?
I'm trying to achieve this:
foo <- function(bar){
x <- bar
rm(bar, envir = environment())
print(c(x, is.null(bar)))
}
Because I want the function to be able to handle multiple inputs.
Specifically I'm trying to pass either a dataframe or a vector to the function, and if I'm passing a dataframe I want to set the vector to NULL for later error handling.
If you want, you can watch my DepthPlotter script, where I want to let the second function check if depth is a dataframe, and if so, assign it to df in stead and remove depth from the environment.
Here is a very brief sketch of how to set this up using S3 method dispatch.
First, you define your generic:
DepthPlotter <- function(depth,...){
UseMethod("DepthPlotter", depth)
}
Then you define methods for specific classes of the argument depth. As a very basic example in your case, you might create only two, a data.frame method and a default method to handle the vector case:
DepthPlotter.default <- function(depth, variable, ...){
#Here you write a function assuming that depth is
# anything but a data frame
}
DepthPlotter.data.frame <- function(depth,...){
#Here you'd write a function that assumes
# that depth is a data frame
}
And then you can call DepthPlotter() using either type of argument and the correct function will be run based upon the result of class(depth).
The example I've sketched out here is a little crude, since I've used a default method to handle the vector case. You could write .numeric and .integer methods to handle numeric or integer vectors more specifically. In my example, the .default method will be called for any case other than data.frame, so if you go this route you'd want to write some code in there that checks for strange cases like depth being a complicated list, or other odd object, if you think there's a chance something like that might be passed to the function.
I am new to R and mostly working with old code written by someone else. And I am trying to create my own R functions.
I found some of the following code used for eigenvalue decomposition.
eigenMatrix = eigen(myMatrix)[[2]]
eigenVals = eigen(myMatrix)[[1]]
Here there is single function that can output 2 different data structures, being, a vector and a matrix depending of the value in the brackets.
When I search of functions with multiple outputs, they usually use lists to output multiple variables at once which does not work, possibly because of different types.
I don't understand why there are two setts of brackets and how the underlying function would work.
The posted code takes the eigen function, which returns a list with 2 values.
Then the [[]] are use to extract the first and second items from the list.
The [[]] is needed to return the underlying structure, and is better explained here: How to Correctly Use Lists in R?
Also, since the eigen function is run twice the code in the question is inefficient.
resultList = eigen(myMatrix)
eigenMatrix = resultList[[2]]
eigenVals = resultList[[1]]
This code is better since eigen is run only once and saves the result of the function as a list and then reads the values from the list.
For the function itself can be coaded as any function with multiple outputs such as here: https://stat.ethz.ch/pipermail/r-help/2007-March/126851.html or here: How to assign from a function with multiple outputs?
The list values can hold any structure and [[]] can be used to return the underlying structure of each value.
I am searching for a fast and simple way to give comprehensible names to the columns of a VAR-coefficient matrix.
What I would like to use is the function VAR.names, which is used in the function VAR.est() in the VAR.etp-package. When I use the function VAR.est(), this works perfectly, but as soon as I modify VAR.est (by adding another element to the list of values which are returned), I receive an error message stating "could not find function VAR.names".
I could not find any information on the function VAR.names.
Example:
library(VAR.etp)
data(dat)
M=VAR.est(dat,p=2,type="const")
M$coef
Another possibility would be to use a loop as in the function VAR() from the vars package, but if VAR.names would actually work, this would be a lot more elegant!
I am a newbie in R trying to write a function to add elements to a list.
Below is the code for the function varNames. I can call it with varNames("name1") but "name1" is not added to "listNames" (this still remains as an empty list).
I've been trying a few things, and searching for answers for a long time, with no success.
Also tried lappend, with no success.
listNames<-list()
varNames<- function(name){
listNames <- c(listNames, name)
}
R is a functional language, which generally means that you pass objects to functions and those functions return some object back, which you can do with as you wish. So, your intended result is a function like:
varNames <- function(existinglist, itemtoadd){
returnvalue <- c(existinglist, itemtoadd)
return(returnvalue)
}
listNames <- list()
a <- 'a'
varNames(existinglist = listNames, itemtoadd = a)
If you want to replace your original listNames object with the return value of the function, then you need to assign it into that original object's name:
listNames
listNames <- varNames(existinglist = listNames, itemtoadd = a)
listNames
The way you've originally written your code is a common error among those new to R. You're trying to create what's known as a "side effect". That is, you want to modify your original listNames object in place without using a <- assignment. This is typically considered bad practice and there are relatively few functions in R that produce side effects like that.
To understand this better, you may find the R Introduction on scope and on assignment within functions helpful, as well as Circle 6 of R Inferno.
The problem is with scope. The listNames in the function is local to that function. Essentially, it is a different object from the listNames you want to change.
There are a few ways to get around this:
Change the value of listNames to the output of the function varNames():
listNames <- varNames(name)
Use <<- and get() to change the value of the listNames in the outer scope. This is generally a bad idea as it makes debuggin very hard.
Don't encapsulate the c() function in the first place.