[R] Get object name inside lapply

Ben Tupper ben.bighair at gmail.com
Thu Feb 25 22:43:05 CET 2016


Hi,

Using your example (note I called the list 'z')...

z <-list(a = seq(1:5), b = seq(10:20))

I picture lapply as extracting each element of z like this z[[i]] - the `[[` extracts the ith value from the context of residing in a list - hence it's name is 'lost' in the new context.  That's different than z[i] which extracts a list of elements.  Try..

z[['a']]  vs. z['a']

As an alternative and depending upon what you really want to do, you could iterate through the names of the list, and pass the list as a parameter.  

r <- lapply(names(z),
    function(nm, dat = NULL){
        sprintf("%s has %i elements", nm, length(dat[[nm]]) )
    },
    dat = z)
r
[[1]]
[1] "a has 5 elements"

[[2]]
[1] "b has 11 elements"

Ben

> On Feb 25, 2016, at 4:27 PM, Mohammad Tanvir Ahamed via R-help <r-help at r-project.org> wrote:
> 
> Hello, 
> 
> I want to get object name of a list inside lapply 
> 
>> c<-list(a=seq(1:5),b=seq(10:20)) 
>> lapply(c,names) 
> $a 
> NULL 
> 
> $b 
> NULL 
> 
> Why NULL ? 
> 
> but i am expecting the names of object . Any help will be appreciated . 
> 
> I want to grab the names of object inside lapply for further process. 
> 
> Thanks . 
> 
> 
> Tanvir Ahamed 
> Göteborg, Sweden  |  mashranga at yahoo.com
> 
> ______________________________________________
> R-help at r-project.org mailing list -- To UNSUBSCRIBE and more, see
> 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