Built-in functions in R can be used in formula objects, for example
例如,R中的内置函数可用于公式对象
reg1 = lm(y ~ log(x), data = data1)
How can I write my functions such that they can be used in formula objects?
如何编写我的函数,以便它们可以在公式对象中使用?
fnMyFun = function(x) {
return(x^2)
}
reg2 = lm(y ~ fnMyFun(x), data = data1)
1 个解决方案
#1
2
What you've got certainly works. One problem is that different modelling functions handle formulas in different ways. I think that as long as you return something that model.matrix
can make sense of, you'll be fine. That would mean
你所得到的确实有效。一个问题是不同的建模函数以不同的方式处理公式。我认为,只要你返回一些model.matrix可以理解的东西,你就没事了。那意味着
-
The function is vectorised; ie given a vector of length N, it returns a result also of length N
该函数是矢量化的;即,给定长度为N的向量,它返回长度为N的结果
-
It has to return an atomic vector or matrix (but not a list, or of type
raw
)它必须返回原子矢量或矩阵(但不是列表,或原始类型)
#1
2
What you've got certainly works. One problem is that different modelling functions handle formulas in different ways. I think that as long as you return something that model.matrix
can make sense of, you'll be fine. That would mean
你所得到的确实有效。一个问题是不同的建模函数以不同的方式处理公式。我认为,只要你返回一些model.matrix可以理解的东西,你就没事了。那意味着
-
The function is vectorised; ie given a vector of length N, it returns a result also of length N
该函数是矢量化的;即,给定长度为N的向量,它返回长度为N的结果
-
It has to return an atomic vector or matrix (but not a list, or of type
raw
)它必须返回原子矢量或矩阵(但不是列表,或原始类型)