[R] lapply to list of variables

Kenn Konstabel lebatsnok at gmail.com
Thu Nov 10 10:53:15 CET 2011

Hi hi,

It is much easier to deal with lists than a large number of separate
objects. So the first answer to your question

> How can I apply a function to a list of variables.

.. 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 ...

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:

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 ...

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

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)


On Tue, Nov 8, 2011 at 6:59 PM, Ana <rrasterr at gmail.com> wrote:
> Hi
> Can someone help me with this?
> How can I apply a function to a list of variables.
> something like this
> listvar=list("Monday","Tuesday","Wednesday")
> func=function(x){x[which(x<=10)]=NA}
> lapply(listvar, func)
> were
> Monday=[213,56,345,33,34,678,444]
> Tuesday=[213,56,345,33,34,678,444]
> ...
> in my case I have a neverending list of vectors.
> Thanks!
> ______________________________________________
> R-help at r-project.org mailing list
> https://stat.ethz.ch/mailman/listinfo/r-help
> PLEASE do read the posting guide http://www.R-project.org/posting-guide.html
> and provide commented, minimal, self-contained, reproducible code.

More information about the R-help mailing list