来自混合效应模型的GGPLOT2中的ACF图
我正在尝试在ggplot2
中执行自相关图。
library(nlme)
fm2 <- lme(distance ~ age + Sex, data = Orthodont, random = ~ 1)
plot(ACF(fm2,resType="normalized"),alpha=0.05)
########################## IC ###########################
ic_alpha= function(alpha, acf_res){
return(qnorm((1 + (1 - alpha))/2)/sqrt(acf_res$n.used))
}
#################### graphics ###########################
library(ggplot2)
ggplot_acf_pacf= function(res_, lag, label, alpha= 0.05){
df_= with(res_, data.frame(lag, ACF))
lim1= ic_alpha(alpha, res_)
lim0= -lim1
ggplot(data = df_, mapping = aes(x = lag, y = ACF)) +
geom_hline(aes(yintercept = 0)) +
geom_segment(mapping = aes(xend = lag, yend = 0)) +
labs(y= label) +
geom_hline(aes(yintercept = lim1), linetype = 2, color = 'blue') +
geom_hline(aes(yintercept = lim0), linetype = 2, color = 'blue')
}
######################## result ########################
acf_ts = ggplot_acf_pacf(res_= ACF(fm2,resType="normalized"),
20,
label= "ACF")
但是,我正在遇到以下错误:
Error in sqrt(acf_res$n.used) :
non-numeric argument to mathematical function
I'm trying to perform an autocorrelation plot in ggplot2
.
library(nlme)
fm2 <- lme(distance ~ age + Sex, data = Orthodont, random = ~ 1)
plot(ACF(fm2,resType="normalized"),alpha=0.05)
Result through the above function:
########################## IC ###########################
ic_alpha= function(alpha, acf_res){
return(qnorm((1 + (1 - alpha))/2)/sqrt(acf_res$n.used))
}
#################### graphics ###########################
library(ggplot2)
ggplot_acf_pacf= function(res_, lag, label, alpha= 0.05){
df_= with(res_, data.frame(lag, ACF))
lim1= ic_alpha(alpha, res_)
lim0= -lim1
ggplot(data = df_, mapping = aes(x = lag, y = ACF)) +
geom_hline(aes(yintercept = 0)) +
geom_segment(mapping = aes(xend = lag, yend = 0)) +
labs(y= label) +
geom_hline(aes(yintercept = lim1), linetype = 2, color = 'blue') +
geom_hline(aes(yintercept = lim0), linetype = 2, color = 'blue')
}
######################## result ########################
acf_ts = ggplot_acf_pacf(res_= ACF(fm2,resType="normalized"),
20,
label= "ACF")
However, I am encountering the following error:
Error in sqrt(acf_res$n.used) :
non-numeric argument to mathematical function
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
由
ACF
产生的对象没有的成员称为n.used
。它具有属性称为n.used
。因此,您的ic_alpha
函数应该是:另一个问题是,由于
ic_alpha
返回向量,因此您将没有一对显着性行,而是每个滞后一对,看起来很混乱。取而代之的是,模拟基本R绘图方法,我们可以使用geom_line
获取单个弯曲对。将导致:
The object produced by
ACF
does not have a member calledn.used
. It has an attribute calledn.used
. So youric_alpha
function should be:Another problem is that, since
ic_alpha
returns a vector, you will not have a single pair of significance lines, but rather one pair for each lag, which looks messy. Instead, emulating the base R plotting method, we can usegeom_line
to get a single curving pair.Which results in: