[R] lapply to list of variables

Dennis Murphy djmuser at gmail.com
Tue Nov 8 21:19:21 CET 2011


Hi:

Here's another way of doing this on the simplified version of your example:

L <- vector('list', 3)      # initialize a list of three components
## populate it
for(i in seq_along(L)) L[[i]] <- rnorm(20, 10, 3)
## name the components
names(L) <- c('Monday', 'Tuesday', 'Wednesday')
## replace values <= 10 with NA
lapply(L, function(x) replace(x, x <= 10, NA)

If you have a large number of atomic objects, you could create a
vector of the object names, make a list out of them (e.g., L <-
list(objnames)) and then mimic the lapply() as above. replace() only
works on vectors, though - Uwe's solution is more general.

HTH,
Dennis

On Tue, Nov 8, 2011 at 8:59 AM, 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