【发布时间】:2014-04-13 23:42:09
【问题描述】:
我正在编写一个函数,我希望能够将向量和公式作为第一个参数。如果是向量,我会做一些单变量计算,如果是公式,我会通过第二个变量分析第一个变量(第二个变量总是一个因素)。
这是我当前的代码:
fun = function(formula,data) {
if (class(with(data,formula))=="formula") {
mod = model.frame(formula,data)
n.group=names(mod)[2]
group <- eval(parse(text=paste("mod$",n.group,sep=""))) #x
response <- model.response(mod) # y
return(table(response,group))
}
else {
return(table(with(data,formula)))
}
}
data(iris)
fun(Sepal.Length~Species,iris) # works correctly
fun(Sepal.Length,iris) # returns an error
返回值仅作说明。
干杯!
【问题讨论】:
-
with(fun(Sepal.Length, iris)), "Error in eval(expr, envir, enclos) : object 'Sepal.Length' not found" 应该很好地表明了错误。 -
对不起,
with(iris, fun(Sepal.Length, iris))