6

This post is based on this question:(Iterate over list to get value by its name)

I'll reproduce it here:

test_list <- list(list("name"="A","property"=1),
              list("name"="B","property"=2),
              list("name"="C","property"=3))

The original OP found:

sapply(test_list, `$`, "property")

only return NULL values. It gives correct results if when use [[ instead as commented by jogo:

> sapply(test_list, `$`, "property")
[[1]]
NULL

[[2]]
NULL

[[3]]
NULL

> sapply(test_list, `[[`, "property")
[1] 1 2 3

This also does not work:

> sapply(test_list, function(x, y) `$`(x, y), y = "property")
[[1]]
NULL

[[2]]
NULL

[[3]]
NULL

However, both $ and [[ works on a single element of test_list:

> `$`(test_list[[1]], 'property')
[1] 1
> `[[`(test_list[[1]], 'property')
[1] 1

I wonder why $ and [[ behave differently when used as FUN= argument for lapply/sapply.

mt1022
  • 16,834
  • 5
  • 48
  • 71
  • This one works: `sapply(test_list, function(x) `$`(x, "property"))`. There are backquotes around the dollar sign. – Rui Barradas May 24 '18 at 14:12
  • @RuiBarradas thanks for the hint. It seems `$(x, y)` is doing something like `x$"y"` without even evaluating `y`. There isnot any `"y"` element so that we only get `NULL`. See MrFlick's answer to the linked question for more details. – mt1022 May 24 '18 at 14:43
  • 1
    Answered e.g. here [link1](https://stackoverflow.com/questions/42560090/what-is-the-meaning-of-the-dollar-sign-in-r-function) or here [link2](https://www.r-bloggers.com/r-accessors-explained/). The two subsetting operators are not equal in their functionality. – Radim May 24 '18 at 14:43
  • @RadimHladik, very helpful. The link2 well-summarized the differences between `$`and `[[`. – mt1022 May 24 '18 at 14:48

0 Answers0