我正在尝试在ggplot2中使用GAM平滑。根据此对话和此代码,仅当n> = 1000时,ggplot2才会加载用于通用加性模型的mgcv软件包。否则,用户必须手动加载该软件包。据我了解,对话中的示例代码应使用进行平滑处理geom_smooth(method="gam", formula = y ~ s(x, bs = "cs")):
library(ggplot2)
dat.large <- data.frame(x=rnorm(10000), y=rnorm(10000))
ggplot(dat.large, aes(x=x, y=y)) + geom_smooth()
Run Code Online (Sandbox Code Playgroud)
但是我得到一个错误:
geom_smooth: method="auto" and size of largest group is >=1000, so using gam with formula: y ~ s(x, bs = "cs"). Use 'method = x' to change the smoothing method.
Error in s(x, bs = "cs") : object 'x' not found
Run Code Online (Sandbox Code Playgroud)
如果尝试以下操作,则会发生相同的错误:
ggplot(dat.large, aes(x=x, y=y)) + geom_point() + geom_smooth(method="gam", formula = y ~ s(x, bs = "cs"))
Run Code Online (Sandbox Code Playgroud)
但是例如线性模型会起作用:
ggplot(dat.large, aes(x=x, y=y)) + geom_smooth(method = "lm", formula = y ~ x)
Run Code Online (Sandbox Code Playgroud)
我在这里做错了什么?
我的R和软件包版本应该是最新的:
R version 3.0.3 (2014-03-06)
Platform: x86_64-apple-darwin10.8.0 (64-bit)
other attached packages: mgcv_1.7-29 ggplot2_0.9.3.1
Run Code Online (Sandbox Code Playgroud)
问题是我summary分配的功能与s我的一样.Rprofile。这混淆了s()函数中的参数gam。我猜应该避免分配太多速记。删除该分配后,一切正常。
避免使.Rprofile速记混淆软件包的一种方法是将它们分配给隐藏环境,并将该环境附加到.Rprofile中。例如(代码是从此处借来的):
.env <- new.env()
.env$s <- base::summary
attach(.env)
Run Code Online (Sandbox Code Playgroud)
然后s将工作summary直到加载mgcv
dat.large <- data.frame(x=rnorm(10000), y=rnorm(10000))
s(dat.large)
x y
Min. :-3.823756 Min. :-4.531882
1st Qu.:-0.683730 1st Qu.:-0.687335
Median :-0.006945 Median :-0.009993
Mean :-0.010285 Mean :-0.000491
3rd Qu.: 0.665435 3rd Qu.: 0.672098
Max. : 3.694357 Max. : 3.647825
Run Code Online (Sandbox Code Playgroud)
并且会在加载程序包后更改含义,但不会混淆程序包功能:
ggplot(dat.large, aes(x=x, y=y)) + geom_smooth() # works
s(dat.large)
$term
[1] "dat.large"
$bs.dim
[1] -1
$fixed
[1] FALSE
$dim
[1] 1
$p.order
[1] NA
$by
[1] "NA"
$label
[1] "s(dat.large)"
$xt
NULL
$id
NULL
$sp
NULL
attr(,"class")
[1] "tp.smooth.spec"
Run Code Online (Sandbox Code Playgroud)
上面的EDIT变通办法似乎在我的实际代码中不起作用,这要复杂得多。如果您想保留该summary缩写,最简单的解决方法是rm(s)在加载mgcv之前放置。
| 归档时间: |
|
| 查看次数: |
3051 次 |
| 最近记录: |