美元运算符作为sapply的函数参数未按预期工作 [英] Dollar operator as function argument for sapply not working as expected

查看:75
本文介绍了美元运算符作为sapply的函数参数未按预期工作的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下列表

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

,我想提取列表元素名称为a的所有元素.

我可以通过

sapply(test_list,`[[`,"a")

这给我正确的结果

#[1] 1 3

当我用卢比元运算符$尝试相同操作时,我得到NULL

sapply(test_list,`$`,"a")
#[[1]]
#NULL
#
#[[2]]
#NULL

但是,如果我在test_list的单个元素上使用它,它将按预期工作

`$`(test_list[[1]],"a")
#[1] 1

我在这里错过了明显的东西吗?

解决方案

根据我的判断,这是两件事的结合.

首先,$的第二个元素已匹配但未求值,因此不能为变量. >

第二,当参数传递给函数时,它们将分配给函数调用中的相应变量.传递给sapply时,"a"被分配给变量,因此将不再与$一起使用.我们可以通过运行

来查看

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

这可能会导致类似这样的结果

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

尽管a是变量(甚至尚未分配),但$仍将其与列表中元素的名称匹配.

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.

I can do this via

sapply(test_list,`[[`,"a")

which gives me the correct result

#[1] 1 3

When I try the same with Rs dollar operator $, I get NULL

sapply(test_list,`$`,"a")
#[[1]]
#NULL
#
#[[2]]
#NULL

However, if I use it on a single element of test_list it works as expected

`$`(test_list[[1]],"a")
#[1] 1

Am I missing something obvious here?

解决方案

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.

这篇关于美元运算符作为sapply的函数参数未按预期工作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆