[R] What is this called? lapply(datum,"[[","ColumnName")

R. Michael Weylandt michael.weylandt at gmail.com
Tue Aug 7 23:07:06 CEST 2012


On Tue, Aug 7, 2012 at 2:06 PM, Kevin Chang <kchang01 at uoguelph.ca> wrote:
> Hello R users
>
>
>
> I recently learned how to use this command:
>
>
> lapply(datum,"[[","ColumnName")
>
>
>
> Unfortunately, I don't know how exactly it works, what it's called (in
> particular the "[[" part], and what other things you can do with it
> (retrieve multiple columns?).
>
>
> Given datum is a list of dataframes with the same column, but different
> number of rows,
>
>
>
> lapply(datum,"[[","ColumnName"),
>
>
>
> Returns you a list of a particular column form each of your dataframes from
> datum.
>
>
>
> I think this is a really useful command, and would like to learn more about
> it.
> Unfortunately I don't know what subject or topic it is under and cannot look
> it up in a book.
>
>

To see the help page, type

? `[[`

at your R prompt.

Long story short, when you use syntax like x[3], that's just sugar for

`[`(x, 3)

which tells R to apply the `[` function with arguments "x" and "3". So
when you pass syntax like that to lapply(), it applies the function

`[`( ??, colNames)

 to each element of your list datum in turn putting them in the slot I
marked with double question marks.

It's not so different than something like

lapply(datum, `+`, 3)

to add 3 to each element of datum. This could alternatively be written as

lapply(datum, function(x) x + 3)

and your example could just as easily (and I think more clearly) be written as

lapply(datum, function(x) x[[colName]])


Best,
Michael

>
> Thank you,
>
>
>
> Kevin
>
>
>
> Master of Science Student
>
> Department of Food, Resource and Agricultural Economics
>
> University of Guelph
> Office:    519-824-4120 ext. 58528
>
> Mobile:  226-979-2813
>
>  <http://fare.uoguelph.ca/users/kchang01>
> http://fare.uoguelph.ca/users/kchang01
>
>
>
>
>
>
>         [[alternative HTML version deleted]]
>
> ______________________________________________
> 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