【发布时间】:2013-02-02 17:40:08
【问题描述】:
我正在编写一个函数,我想在其中将一些参数传递给 crrstep 函数('crrstep' 包),但我遇到了一个问题:我的函数中的参数 'event' 在我输入时无法识别在 crrstep 中。我猜 crrstep 看起来与我希望它看起来的环境不同,但是即使在网上搜索了几个小时的解决方案后,我似乎也无法弄清楚如何解决这个问题(我在编程方面非常缺乏经验..) .任何帮助将不胜感激!
这是一些模拟数据(来自 crrstep-documentation 的调整示例)和我的代码示例:
n <- 500
ftime <- rexp(n)
fstatus <- sample(0:2,n,replace=TRUE)
testdata <- matrix(runif(8*n),nrow=n)
testdata <- cbind(ftime,fstatus,testdata)
dimnames(testdata)[[2]] <- c('ftime','fstatus','x1','x2','x3','x4','x5','x6','x7','x8')
testdata <- as.data.frame(testdata)
formula1 <- ftime ~ 1 + x1 + x2 + x3 + x4 + x5 + x6 + x7 + x8
rm(fstatus,ftime,n)
test.fun <- function(x,data,event){
require(crrstep)
select.mod<- crrstep(formula=x,,etype=event, failcode=1, cencode=0,data=data,
direction = "backward", criterion = "AIC", crr.object = TRUE,
trace = FALSE)
#Rest of function omitted for now
print(select.mod)
}
#Test
test.fun(x=formula1,data=testdata,event=fstatus)
#I get: Error in eval(expr, envir, enclos) : object 'event' not found"
非常感谢! 抢
【问题讨论】:
-
问题是你
rm(fstatus)在将它作为event参数传递给你的函数之前...... -
嗨,juba,在我删除 fstatus 之前,我将它添加到了 testdata,然后我在我的函数中将其用作“数据”参数。我以为 crrstep 会在“数据”中查找“事件”(我也将其传递给 crrstep),但不知何故它没有..
-
那么您应该在您的
crrstep()调用中使用etype=data[,event],并将fstatus 参数作为字符串传递:event="fstatus"。 -
当我这样输入时:
test.fun <- function(x,data,event){ require(crrstep) select.mod<- crrstep(formula=x,,etype=data[,event], failcode=1, cencode=0,data=data, direction = "backward", criterion = "AIC", crr.object = TRUE, trace = TRUE) print(select.mod) } test.fun(x=formula1,data=testdata,event="fstatus")我仍然得到一个错误:错误在'[.data.frame'(data, , event) : object 'event' not found -
这两个最近的问题是相关的,也可能有帮助:stackoverflow.com/q/14784302/210673stackoverflow.com/q/14839689/210673
标签: r function environment argument-passing