R 中的替换函数是什么? [英] What are Replacement Functions in R?

查看:59
本文介绍了R 中的替换函数是什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我搜索了参考以了解 R 中的替换函数,但我还没有找到.我试图理解 R 中替换函数的概念.我有下面的代码,但我不明白:

I searched for a reference to learn about replacement functions in R, but I haven't found any yet. I'm trying to understand the concept of the replacement functions in R. I have the code below but I don't understand it:

"cutoff<-" <- function(x, value){
 x[x > value] <- Inf
 x
 }

然后我们调用 cutoff 为:

and then we call cutoff with:

 cutoff(x) <- 65

谁能解释一下 R 中的替换函数是什么?

Could anyone explain what a replacement function is in R?

推荐答案

打电话时

cutoff(x) <- 65

你实际上是在打电话

x <- "cutoff<-"(x = x, value = 65)

函数的名称必须被引用,因为它是一个语法有效但非标准的名称,解析器会将 <- 解释为运算符而不是函数名称的一部分,如果它没有被引用.

The name of the function has to be quoted as it is a syntactically valid but non-standard name and the parser would interpret <- as the operator not as part of the function name if it weren't quoted.

"cutoff<-"() 就像任何其他函数一样(尽管名称很奇怪);它根据 value 对其输入参数进行更改(在这种情况下,它会将 x 中大于 65 的任何值设置为 Inf(无限)).

"cutoff<-"() is just like any other function (albeit with a weird name); it makes a change to its input argument on the basis of value (in this case it is setting any value in x greater than 65 to Inf (infinite)).

当你像这样调用函数时,魔法就真的完成了

The magic is really being done when you call the function like this

cutoff(x) <- 65

因为 R 正在解析它并提取各种位来进行上面显示的真正调用.

because R is parsing that and pulling out the various bits to make the real call shown above.

更一般地说,我们有

FUN(obj) <- value

R 找到函数 "FUN<-"() 并通过将 objvalue 传入 "FUN< 来设置调用;-"() and 安排将 "FUN<-"() 的结果分配回 obj,因此它调用:

R finds function "FUN<-"() and sets up the call by passing obj and value into "FUN<-"() and arranges for the result of "FUN<-"() to be assigned back to obj, hence it calls:

obj <- "FUN<-"(obj, value)

此信息的有用参考是 R 语言定义第 3.4.4 节:子集分配;讨论有点倾斜,但似乎是最官方的参考文献(R FAQ(R和S-PLUS之间的差异)和R语言参考(各种技术问题)中顺便提到了替换函数,但我在官方文档中没有找到任何进一步的讨论).

A useful reference for this information is the R Language Definition Section 3.4.4: Subset assignment ; the discussion is a bit oblique, but seems to be the most official reference there is (replacement functions are mentioned in passing in the R FAQ (differences between R and S-PLUS), and in the R language reference (various technical issues), but I haven't found any further discussion in official documentation).

这篇关于R 中的替换函数是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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