首页 > 解决方案 > 有没有办法重新分配 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 访问器函数并以我在上面的示例中尝试的方式使用它们?

标签: rfunctionfunctional-programmingvariable-assignmentaccessor

解决方案


访问器函数实际上是成对的函数。一个用于检索,一个用于分配。如果你想复制它,你需要复制这两个部分

alt_names_fun <- names
`alt_names_fun<-` <- `names<-`

作业版本<-以他们的名字命名。这是 R 用来查找它们的特殊命名对流。由于这些是基本符号名称中通常不允许使用的字符,因此您需要使用反引号将函数名称括起来。


推荐阅读