0

I have a list of lists, each sublist has dozens of elements and I just want to extract one of them.

x = list(`1` = list(a=1,b=2),`2` = list(a=3,b=4))

There are many ways to accomplish this, but I want to be as clever as possible so I try

lapply(x,`$`,"b")
# $`1`
# NULL
# 
# $`2`
# NULL

but this doesn't work despite the fact that

`$`(x[[1]],"b")
# [1] 2

mapply does work like this:

mapply(`$`,x,MoreArgs=list(name="b"))
# 1 2 
# 2 4 

I can use lapply like this:

 lapply(x,getElement,"b")
 # $`1`
 # [1] 2
 # 
 # $`2`
 # [1] 4 

But why doesn't lapply work with $ the way it ought to?

Abhijit
  • 746
  • 5
  • 18
Mark
  • 4,387
  • 2
  • 28
  • 48
  • 1
    This may be helpful: http://stackoverflow.com/q/18216084/1191259 – Frank Apr 01 '16 at 14:07
  • Thanks @Frank - I saw that before I posted but that's about `lapply`-ing on a subset of the parent list where I want to subset the child lists. – Mark Apr 01 '16 at 14:12
  • As the guy who wrote it, I don't know what you mean about subsets, but that's okay. – Frank Apr 01 '16 at 14:13

1 Answers1

2

You can try

lapply(x,'[[',"b")

$`1`
[1] 2

$`2`
[1] 4
Batanichek
  • 7,761
  • 31
  • 49