[R] $ subset operator behavior in lapply

Andrew Simmons @kw@|mmo @end|ng |rom gm@||@com
Thu Oct 27 18:34:36 CEST 2022


$ does not evaluate its second argument, it does something like
as.character(substitute(name)).

You should be using

lapply(list, function(x) x$a)

or

lapply(list, `[[`, "a")


On Thu, Oct 27, 2022, 12:29 Hilmar Berger <hilmar.berger using gmx.de> wrote:

> Dear all,
>
> I'm a little bit surprised by the behavior of the $ operator when used
> in lapply - any indication what might be wrong is appreciated.
>
> > xx = list(A=list(a=1:3, b=LETTERS[1:3]),"B"=list(a=7:9,
> b=LETTERS[7:9]))  > lapply(xx,`$`,"a") $A NULL $B NULL > `$`(xx[[1]],"a")
> [1] 1 2 3 >
> lapply(xx,`[`,"a") $A $A$a [1] 1 2 3 $B $B$a [1] 7 8 9 Any idea why I
> `$`(object, name) works when applied to the single list element but not
> within lapply (in contrast to `[`)?
> I checked the help page of the extraction operators but could not find
> anything that explains this. Thanks and best regards Hilmar >
> sessionInfo() R version 4.2.1 (2022-06-23) Platform: x86_64-pc-linux-gnu
> (64-bit) Running under: Ubuntu 20.04.5 LTS Matrix products: default
> BLAS: /usr/lib/x86_64-linux-gnu/openblas-pthread/libblas.so.3 LAPACK:
> /usr/lib/x86_64-linux-gnu/openblas-pthread/liblapack.so.3 locale: [1]
> LC_CTYPE=en_US.UTF-8 LC_NUMERIC=C [3] LC_TIME=de_DE.UTF-8
> LC_COLLATE=en_US.UTF-8 [5] LC_MONETARY=de_DE.UTF-8
> LC_MESSAGES=en_US.UTF-8 [7] LC_PAPER=de_DE.UTF-8 LC_NAME=C [9]
> LC_ADDRESS=C LC_TELEPHONE=C [11] LC_MEASUREMENT=de_DE.UTF-8
> LC_IDENTIFICATION=C attached base packages: [1] stats graphics grDevices
> utils datasets methods base loaded via a namespace (and not attached):
> [1] compiler_4.2.1
>
>         [[alternative HTML version deleted]]
>
> ______________________________________________
> R-help using 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.
>

	[[alternative HTML version deleted]]



More information about the R-help mailing list