Skip to content
Prev 276914 / 398506 Next

lapply to list of variables

Hi hi,

It is much easier to deal with lists than a large number of separate
objects. So the first answer to your question
.. might be to convert your "list of variables" to a regular list.
Instead of ...

monday <- 1:3
tuesday <- 4:7
wednesday <- 8:100

... you could have:

mydays <- list(monday=1:3, tuesday=4:7, wednesday=8:100)

... and things will be a lot easier. If you happen to have a thousand
of such variables in your workspace then you can convert them to a
list using ...

listvar=list("Monday","Tuesday","Wednesday")
mylist <- lapply(listvar, get)

... but this is not always nice to you, for example, if you have
variables that have the same names as some functions in base packages.
Try this:

a<-1
b<-2
c<-3
mean<-4
listvar <- c("a", "b", "c", "mean")
lapply(listvar, get)

- a safer way would be lapply(lv, get, envir=.GlobalEnv)
# and for a named list, the best I can think of is:
structure(lapply(lv, get, envir=.GlobalEnv), .Names=lv)

And then ...
do you want actually to change your variables with this? Or just to
have a list with your original variables where any x[x<=10] is set to
NA? In the first case you'll need to do nonstandard tricks that
everyone will say you should avoid (but you can use e.g. `assign`, or
macros - see `defmacro` in package gtools). In the second case you
just need to take care that your function would return a sensible
value. An assignment returns the value that was assigned, in this
case, it is  always NA but if that's not what you meant, you can try

func <- function(x){ x[x<=10] <- NA; x}
lapply(listvar, func)

hth
On Tue, Nov 8, 2011 at 6:59 PM, Ana <rrasterr at gmail.com> wrote: