r - 有没有办法重新分配 R 访问器函数并使用它来更新它访问的变量属性?
问题描述
在我的代码中,我有条件地希望在整个代码中使用一个或另一个访问器函数。每次我想选择使用哪个访问器并对其进行显式编码时,我都没有使用 if-else 语句,而是尝试有条件地将任一访问器函数分配给一个新函数accessor_fun
,并在整个代码中使用它,但这会返回一个当我使用访问器函数重新分配它访问的值时出错。这是我遇到的问题的简化示例:
#reassigning the base r function names to a new function name
alt_names_fun <- names
example_list <- list(cat = 7, dog = 8, fish = 33)
other_example_list <- list(table = 44, chair = 101, desk = 35)
#works
alt_names_fun(example_list)
#throws error
alt_names_fun(example_list) <- alt_names_fun(other_example_list)
#still throws error
access_and_assign <- function(x, y, accessor) {
accessor(x) <- accessor(y)
}
access_and_assign(x = example_list, y = other_example_list, accessor = alt_names_fun)
#still throws error
alt_names_fun_2 <- function(x){names(x)}
alt_names_fun_2(example_list) <- alt_names_fun_2(other_example_list)
#works
names(example_list) <- names(other_example_list)
如您所见,如果您尝试上面的代码,我遇到的错误示例是
Error in alt_names_fun(example_list) <- alt_names_fun(other_example_list) :
could not find function "alt_names_fun<-"
所以我的问题是,有没有办法重新分配 R 访问器函数并以我在上面的示例中尝试的方式使用它们?
解决方案
访问器函数实际上是成对的函数。一个用于检索,一个用于分配。如果你想复制它,你需要复制这两个部分
alt_names_fun <- names
`alt_names_fun<-` <- `names<-`
作业版本<-
以他们的名字命名。这是 R 用来查找它们的特殊命名对流。由于这些是基本符号名称中通常不允许使用的字符,因此您需要使用反引号将函数名称括起来。
推荐阅读
- sublimetext3 - SublimeText 和 ignore_vcs_packages 设置
- python - Django:为什么我必须在我的 AppConfig 中导入信号(它似乎没有工作)
- javascript - 如何在 React-Quill 中设置字符长度
- postgresql - Postgres字符串与前导空格的比较
- html - 用于发送与我的表格格式相同的电子邮件的 Google 应用脚本
- php - 无法在 Symfony 2.3 中更新新的数据库字段
- php - 如何修复 PHP 数组爆炸结果在表单选择中仅显示最后一个值?
- unit-testing - 为什么从 npm 运行 Jest 时,我的覆盖率为 0?
- swift - Swift firebase 查询有序搜索
- r - 如何将 app.R 的输入传递给其他脚本并返回对象?