[R] stupid R tricks

Carlos J. Gil Bellosta cgb at datanalytics.com
Sun Nov 21 22:07:43 CET 2010


On 11/07/2010 08:06 PM, David Winsemius wrote:
>
> On Nov 7, 2010, at 12:25 PM, David Winsemius wrote:
>
>>
>> On Nov 7, 2010, at 11:40 AM, Carl Witthoft wrote:
>>
>>> Hi all,
>>> Just thought I'd post this (maybe) helpful tool I wrote. For people
>>> like me who are bad at keeping a clean environment, it's a time-saver.
>>>
>>> #simple command to get only one type of object in current environment
>>> lstype<-function(type='closure'){
>>> inlist<-ls(.GlobalEnv)
>>> if (type=='function') type <-'closure'
>>> typelist<-sapply(sapply(inlist,get),typeof)
>>> return(names(typelist[typelist==type]))
>>> }
>>
>> As a fellow messy-enviromnetalist that was useful. Here's a similar
>> function that returns a vector of object names belonging to a
>> particular (single) class:
>>
>> > getclass <- function(cls) ls(envir=.GlobalEnv)[
>> sapply(ls(envir=.GlobalEnv), function(x) class(eval(parse(text=x))) )
>> == cls ]
>
> Here is a version that substitutes get(...) for eval(parse(text= ...)
> making it a bit less subject to "fortune hunters" and removes the
> limitation to one-class objects:
>
> getclass <- function(cls="data.frame") ls(envir=.GlobalEnv)[
> sapply(
> sapply(ls(envir=.GlobalEnv), function(x) class(get(x)) ),
> function(y) cls %in% y) ]
>

Hello,

A simpler, less verbose version:

getclass <- function(cls="data.frame")
     Filter( function( b ) any( cls  %in% class( get( b ) ) ), ls( 
envir=.GlobalEnv ) )

Best regards,

Carlos J. Gil Bellosta
http://www.datanalytics.com



More information about the R-help mailing list