Dollar operator as function argument for sapply not working as expected

后端 未结 2 1636
遥遥无期
遥遥无期 2021-02-13 16:17

I have the following list

test_list=list(list(a=1,b=2),list(a=3,b=4))

and I want to extract all elements with list element name a.

2条回答
  •  失恋的感觉
    2021-02-13 16:49

    From what I've been able to determine it's a combination of two things.

    First, the second element of $ is matched but not evaluated so it cannot be a variable.

    Secondly, when arguments are passed to functions they are assigned to the corresponding variables in the function call. When passed to sapply "a" is assigned to a variable and therefore will no longer work with $. We can see this by occurring by running

    sapply("a", print)
    [1] "a"
      a 
    "a"
    

    This can lead to peculiar results like this

    sapply(test_list, function(x, a) {`$`(x, a)})
    [1] 1 3
    

    Where despite a being a variable (which hasn't even been assigned) $ matches it to the names of the elements in the list.

提交回复
热议问题