1

我正在尝试在 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() 

但我收到一个错误:

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

如果我尝试以下操作,也会发生同样的错误:

ggplot(dat.large, aes(x=x, y=y)) + geom_point() + geom_smooth(method="gam", formula = y ~ s(x, bs = "cs"))

但例如线性模型会起作用:

ggplot(dat.large, aes(x=x, y=y)) + geom_smooth(method = "lm", formula = y ~ x)

我在这里做错了什么?

我的 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 
4

2 回答 2

5

问题是我在我summary的. 这混淆了函数中的参数。我想应该避免分配太多的速记。删除该分配后,一切正常。s.Rprofiles()gam

避免使包被 .Rprofile 简写混淆的一种方法是将它们分配给隐藏环境并将该环境附加到 .Rprofile 中。例如(代码是从这里借来的):

.env <- new.env()
.env$s <- base::summary
attach(.env)

然后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  

并且会在加载包后改变含义,但不会混淆包的功能:

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"

上面的编辑解决方法似乎在我的实际代码中不起作用,这要复杂得多。如果您想保留该summary速记,最简单的解决方法就是rm(s)在加载mgcv之前放置。

于 2014-04-25T09:12:14.137 回答
1

我的问题是由损坏的mgcv版本引起的。重新安装这个包解决了这个问题:

install.packages("mgcv")

版本:

  • Linux Mint 18 / 18.1
  • R 3.4.0

我在两台不同的 Linux 机器上遇到了同样的问题。

于 2017-07-09T01:30:01.500 回答