【发布时间】:2014-08-19 13:56:26
【问题描述】:
我不明白 R 的输出。似乎我明确定义的对象outcome 没有找到,虽然它在子功能中成功使用并打印出来。这怎么可能?
我的 R 代码:
f.hazardratio <- function(input)
{
outcome <- c("A","B","C","D","E","F")
category <- c(rep("surv",2),rep("term",2),rep("lobw",2))
for(i in 1:length(outcome))
{
if(nrow(subset(input,input[,paste("out",category[i],sep=".")]==outcome[i]))>0)
{
lex <- f.lexis(data=input,
out=category[i],
out.case=outcome[i])
print(str(lex))
print(outcome[i])
print(head(subset(lex, lex.Xst=="A")))
print(head(subset(lex, lex.Xst==outcome[i])))
# nrow(subset(lex, lex.Xst==outcome[i])) is the value I am actually interest in and causes the same error message as print(), which I only added for identifying the problem
# code continues, but not shown ...
}
}
}
还有输出:
Classes ‘Lexis’ and 'data.frame': 107455 obs. of 6 variables:
$ pre.time : num
$ lex.dur : num
$ lex.Xst : Factor w/ 3 levels
$ lex.Cst : Factor w/ 3 levels
[1] "A"
pre.time lex.dur lex.Xst lex.Cst
930 145 36 A vv
2255 273 14 A vv
4842 115 99 A vv
5127 260 30 A vv
5217 71 108 A v
5422 152 2 A vv
Error in eval(expr, envir, enclos) (from #32) : object 'outcome' not found
我已经尝试将变量类型从因子更改为字符,反之亦然,并尝试定义一个中间临时变量tmp <- outcome[i]。不幸的是,到目前为止没有任何效果。
【问题讨论】:
-
你能提供一个可重现的例子吗?您是否尝试过任何其他类型的子集,例如
xy <- data.frame(x = runif(10), y = letters[1:10]);mysub <- c("a", "b", "c");xy[xy$y %in% mysub, ]? -
有什么问题?您无权在您的函数之外访问
Lex,或者您不确定为什么print(outcome[i])为 False?exists("string")检查评估的字符串是否存在。变量"A", "B"...."F"确实不存在,但您的代码应该可以正常工作。 -
问题是循环中的第五个打印语句,
lex在范围内。outcome[i]是“A”,使用“A”进行子集显式有效,使用outcome[i](刚刚打印为“A”)进行子集无效。 -
使用中间变量
tmp,正确的语法是print(exists("tmp"))而不是print(exists(tmp))。 -
我刚刚复制了您的代码结构,并尽我所能编写了丢失的函数并猜测了丢失的数据,但我无法得到 barf 的子集。鉴于您的代码 至少有一个 缺少右花括号,我猜我们在这里浪费时间。
subset可以创建范围问题(这就是为什么我喜欢明确并使用方括号的原因)但是您没有给我们足够的复制。
标签: r