[R] Get object name inside lapply
peter dalgaard
pdalgd at gmail.com
Fri Feb 26 11:00:54 CET 2016
On 25 Feb 2016, at 22:43 , Ben Tupper <ben.bighair at gmail.com> wrote:
> 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']
>
Exactly. lapply applies the function to each _element_ in turn, not to a list containing one element. To further understand why the names do not carry onto elements, contemplate things like
z <- list(a=c(b=1))
names(z[[1]])
> 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"
>
Or,
> mapply(z,names(z), FUN=function(e,n) sprintf("%s has %i elements", n, length(e)))
a b
"a has 5 elements" "b has 11 elements"
and variation thereof.
-pd
> 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.
>
> ______________________________________________
> 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.
--
Peter Dalgaard, Professor,
Center for Statistics, Copenhagen Business School
Solbjerg Plads 3, 2000 Frederiksberg, Denmark
Phone: (+45)38153501
Office: A 4.23
Email: pd.mes at cbs.dk Priv: PDalgd at gmail.com
More information about the R-help
mailing list