[R] A question on list and lapply

MacQueen, Don macqueen1 at llnl.gov
Mon Dec 17 17:20:20 CET 2012


If you don't need the "P" element in the output, then I think the answers
you've already received are good.

But if you do want to retain the "P" element, then I think it's better to
simply add the missing elements back in after using lapply. The code will
be easier to understand a year from now. Here's what I would do:

Dat <- vector("list", length = 26)
names(Dat) <- LETTERS

exclude <- c('P','Z')
tmp1 <- Dat[ setdiff(names(Dat), exclude) ]
tmp2 <- Dat[ intersect(names(Dat), exclude) ]

myfun <- function(x) rnorm(5)  ## return() not needed
Dat1 <- c( lapply(tmp1, myfun) , tmp2)

## put back in original order if desired
Dat1 <- Dat1[ names(Dat) ]

Is there a "direct way" to achieve this *and* include the 'P' element in
Dat1? Not that I know of.


-- 
Don MacQueen

Lawrence Livermore National Laboratory
7000 East Ave., L-627
Livermore, CA 94550
925-423-1062





On 12/14/12 10:58 AM, "Christofer Bogaso" <bogaso.christofer at gmail.com>
wrote:

>Dear all, let say I have following list:
>
>Dat <- vector("list", length = 26)
>names(Dat) <- LETTERS
>My_Function <- function(x) return(rnorm(5))
>Dat1 <- lapply(Dat, My_Function)
>
>
>However I want to apply my function 'My_Function' for all elements of
>'Dat' except the elements having 'names(Dat) == "P"'. Here I have
>specified the name "P" just for illustration however this will be some
>name specified by user.
>
>Is there any direct way to achieve this, using 'lapply'?
>
>Thanks for your help.
>
>______________________________________________
>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