6
我使用tryCatch
很多来捕获我的R代码中的潜在错误消息,但我今天遇到了一个奇怪的问题ggplot
- 我真的不知道发生了什么事情(即使经过一段时间Google/SO搜索)。tryCatch和ggplot
简单实例与不完全ggplot
呼叫(无添加层):
> tryCatch(eval(parse(text = 'ggplot(mtcars, aes(x=hp, y=wt))')), error = function(e) e)
Error: No layers in plot
所以误差不会捕获。更:我得到R对象与ggplot
类:
> str(tryCatch(eval(parse(text = 'ggplot(mtcars, aes(x=hp, y=wt))')), error = function(e) e))
List of 8
$ data :'data.frame': 32 obs. of 11 variables:
..$ mpg : num [1:32] 21 21 22.8 21.4 18.7 18.1 14.3 24.4 22.8 19.2 ...
..$ cyl : num [1:32] 6 6 4 6 8 6 8 4 4 6 ...
..$ disp: num [1:32] 160 160 108 258 360 ...
..$ hp : num [1:32] 110 110 93 110 175 105 245 62 95 123 ...
..$ drat: num [1:32] 3.9 3.9 3.85 3.08 3.15 2.76 3.21 3.69 3.92 3.92 ...
..$ wt : num [1:32] 2.62 2.88 2.32 3.21 3.44 ...
..$ qsec: num [1:32] 16.5 17 18.6 19.4 17 ...
..$ vs : num [1:32] 0 0 1 1 0 1 0 1 1 1 ...
..$ am : num [1:32] 1 1 1 0 0 0 0 0 0 0 ...
..$ gear: num [1:32] 4 4 4 3 3 3 3 4 4 4 ...
..$ carb: num [1:32] 4 4 1 1 2 1 4 2 2 4 ...
$ layers : list()
$ scales :Reference class 'Scales' [package "ggplot2"] with 1 fields
..$ scales: NULL
..and 20 methods, of which 9 are possibly relevant:
.. add, clone, find, get_scales, has_scale, initialize, input, n,
.. non_position_scales
$ mapping :List of 2
..$ x: symbol hp
..$ y: symbol wt
$ options :List of 1
..$ labels:List of 2
.. ..$ x: chr "hp"
.. ..$ y: chr "wt"
$ coordinates:List of 1
..$ limits:List of 2
.. ..$ x: NULL
.. ..$ y: NULL
..- attr(*, "class")= chr [1:2] "cartesian" "coord"
$ facet :List of 1
..$ shrink: logi TRUE
..- attr(*, "class")= chr [1:2] "null" "facet"
$ plot_env :<environment: R_GlobalEnv>
- attr(*, "class")= chr "ggplot"
任何想法捕捉到这些样的错误?
更新:我知道的一个事实,即上面的调用可能会在某些情况下,OK(像后来添加层)。但是,那么请考虑下面的例子(请注意,我们有一个错字有:t
提供在y
轴代替wt
):
> tryCatch(eval(parse(text = 'ggplot(mtcars, aes(x=hp, y=t)) + geom_point()')), error = function(e) e)
Error in data.frame(x = c(110, 110, 93, 110, 175, 105, 245, 62, 95, 123, :
arguments imply differing number of rows: 32, 0
我得到错误信息,但是这不是tryCatch
抓获。
真棒,非常感谢!我怎么会错过这个? :) 看过你的第一行后,这很明显,但这个问题在那之前给了我几个小时的头痛。所以总之:再次感谢:) – daroczig 2012-08-02 16:54:58
很高兴我能帮忙!有时候我们可能会太接近代码... – Andrie 2012-08-02 16:59:37