Identify all objects of given class for further processing
Use the class
function:
Models <- Filter( function(x) 'lm' %in% class( get(x) ), ls() )
lapply( Models, function(x) plot( get(x) ) )
(Modified slightly to handle situations where objects can have multiple classes, as pointed out by @Gabor in the comments).
Update. For completeness, here is a refinement suggested by @Gabor's comment below. Sometimes we may want to only get objects that are of class X but not class Y. Or perhaps some other combination. For this one could write a ClassFilter()
function that contains all of the class filterling logic, such as:
ClassFilter <- function(x) inherits(get(x), 'lm' ) & !inherits(get(x), 'glm' )
Then you get the objects that you want:
Objs <- Filter( ClassFilter, ls() )
Now you can process the Objs
whatever way you want.
Only list objects in class data.frame
Based on the link @Chase provided in the comments, you can Filter
the results of ls
to only include the names of objects that inherit
the data.frame
class.
#R --vanilla -q
a <- data.frame(1:3)
b <- data.frame(1:2, 4:3)
L <- list(a, b)
Filter(function(x) inherits(get(x), "data.frame"), ls())
#[1] "a" "b"
R sub-setting the list of objects in the global environment by class
You could retrieve ls()
and check the class of everything. It may not be particularly efficient though, as it does the filtering after ls()
and not within.
# populate global environment with some vars.
rm(list=ls())
a <- 1
b <- 2
c <- 'foo'
d <- 'asdf'
lst <- ls()
# return everything 'numeric':
lst[sapply(lst,function(var) any(class(get(var))=='numeric'))]
# 'a' 'b'
The get(var)
gets the variable corresponding to the string in var
, so if var
is "a"
then get(var)
retrieves 1 (being the value of variable a
).
As @VincentZoonekynd notes below - it is possible for objects to have multiple classes. Soo class(some_xts_object)
is c("xts","zoo")
-- the above method will return some_xts_object
if you search for xts
objects, but also if you search for zoo
objects.
Use ls() or objects() to get objects of class data.frame
The answer given by @jverzani about figuring out which objects are data frames is good. So let's start with that. But we want to select only the items that are data.frames. So we could do that this way:
#test data
df <- data.frame(a=1:10, b=11:20)
df2 <- data.frame(a=2:4, b=4:6)
notDf <- 1
dfs <- ls()[sapply(mget(ls(), .GlobalEnv), is.data.frame)]
the names of the data frames are now strings in the dfs object so you can pass them to other functions like so:
sapply( dfs, function(x) str( get( x ) ) )
I used the get()
command to actually get the object by name (see the R FAQ for more about that)
I've answered your qeustion above, but I have a suspicion that if you would organize your data frames into list items your code would be MUCH more readable and easy to maintain. Obviously I can't say this with certainty, but I can't come up with a use case where iterating through all objects looking for the data frames is superior to keeping your data frames in a list and then calling each item in that list.
Is there a simple way of obtaining all object instances of a specific class in Java
The debugger in Eclipse can show you all the instances of a class, so I looked around Eclipse's sources. Eclipse uses the Java Debug Wire Protocol, which allows you (since Java 6) to look up all the instances of the requested class. If you want to go down this path, grab a copy of Eclipse sources and check out the instances
method of org.eclipse.jdi.internal.ReferenceTypeImpl
.
A simpler way is to use the Java Debug Interface. Note the ReferenceType.instances
method.
I still haven't figured out how to use JDI to connect to a running process and how to obtain an instance of ReferenceType
. The JDK contains several examples, so I'm sure it's doable.
Print all properties of a Python Class
In this simple case you can use vars()
:
an = Animal()
attrs = vars(an)
# {'kids': 0, 'name': 'Dog', 'color': 'Spotted', 'age': 10, 'legs': 2, 'smell': 'Alot'}
# now dump this in some way or another
print(', '.join("%s: %s" % item for item in attrs.items()))
If you want to store Python objects on the disk you should look at shelve — Python object persistence.
At runtime, find all classes in a Java application that extend a base class
I use org.reflections:
Reflections reflections = new Reflections("com.mycompany");
Set<Class<? extends MyInterface>> classes = reflections.getSubTypesOf(MyInterface.class);
Another example:
public static void main(String[] args) throws IllegalAccessException, InstantiationException {
Reflections reflections = new Reflections("java.util");
Set<Class<? extends List>> classes = reflections.getSubTypesOf(java.util.List.class);
for (Class<? extends List> aClass : classes) {
System.out.println(aClass.getName());
if(aClass == ArrayList.class) {
List list = aClass.newInstance();
list.add("test");
System.out.println(list.getClass().getName() + ": " + list.size());
}
}
}
Python multiprocessing: object identifier unique across processes
You asked, does the id of the object survive the pickling? The answer is no. The object is pickled and sent to another process, and a new object is created in that process with a new id. Results are sent back to the original process. The id does not survive… they are different objects. Id doesn't often survive pickling even in the same process… try obj2 = pickle.loads(pickle.dumps(object))
and see if obj2 is object
… it's often not the case.
>>> import dill
>>>
>>> class A(object):
... pass
...
>>> b = A()
>>>
>>> id(b)
4473714832
>>> id(dill.loads(dill.dumps(b)))
4486366032
>>>
However, if you want to maintain an "id" as to understand which object is which, you can. Just add a id
attribute that stores some id information (could be a simple number, such as the process "rank" (order), or could be something like a randomly generated hash, or something else… you pick). If you create this attribute ahead of time, and store the "id" there, it should maintain this information across a pickle
. However, if you try to dynamically add an id
attribute to any object, then pickle
will "forget" that attribute was added, and the deserialized object will not have the attribute. Alternately, if you use an "advanced" serializer like dill
, you can pickle a dynamically added attribute on a class instance or almost any object.
Related Topics
Data.Frame Without Ruining Column Names
Techniques for Finding Near Duplicate Records
Multiple Graphs in One Canvas Using Ggplot2
R Shiny Rest API Communication
There Is Pmin and Pmax Each Taking Na.Rm, Why No Psum
Merge Rows in a Dataframe Where the Rows Are Disjoint and Contain Nas
Increase Resolution of Color Scale for Values Close to Zero
Access and Preserve List Names in Lapply Function
Adding Greek Character to Axis Title
Finding Out Which Functions Are Called Within a Given Function
Plot Data in Descending Order as Appears in Data Frame
Mean of a Column in a Data Frame, Given the Column's Name
Stacked Bar Chart in R (Ggplot2) with Y Axis and Bars as Percentage of Counts
Speed Up Plot() Function for Large Dataset
Create Zip File: Error Running Command " " Had Status 127
Python's Xrange Alternative for R or How to Loop Over Large Dataset Lazilly