我收到了错误消息:
错误:找不到对象'x'
或者更复杂的版本
均值(x)中的错误:在为函数'mean'选择方法时评估参数'x'时出错:错误:找不到对象'x'
这是什么意思?
Ric*_*ton 27
该错误意味着R无法找到错误消息中提到的变量.
重现错误的最简单方法是键入不存在的变量的名称.(如果已经定义x,请使用其他变量名称.)
x
## Error: object 'x' not found
Run Code Online (Sandbox Code Playgroud)
更复杂的错误版本具有相同的原因:在x不存在时调用函数.
mean(x)
## Error in mean(x) :
## error in evaluating the argument 'x' in selecting a method for function 'mean': Error: object 'x' not found
Run Code Online (Sandbox Code Playgroud)
一旦定义了变量,就不会发生错误.
x <- 1:5
x
## [1] 1 2 3 4 5
mean(x)
## [1] 3
Run Code Online (Sandbox Code Playgroud)
ls() # lists all the variables that have been defined
exists("x") # returns TRUE or FALSE, depending upon whether x has been defined.
Run Code Online (Sandbox Code Playgroud)
当您使用非标准评估时,可能会发生这样的错误.例如,使用时subset,如果数据框中的列名不存在于子集中,则会发生错误.
d <- data.frame(a = rnorm(5))
subset(d, b > 0)
## Error in eval(expr, envir, enclos) : object 'b' not found
Run Code Online (Sandbox Code Playgroud)
如果使用自定义评估,也会发生错误.
get("var", "package:stats") #returns the var function
get("var", "package:utils")
## Error in get("var", "package:utils") : object 'var' not found
Run Code Online (Sandbox Code Playgroud)
在第二种情况下,var当R查看utils包的环境时,无法找到该函数,因为列表utils位于search列表的下方stats.
在更高级的用例中,您可能希望阅读:
demo(scoping)