问题描述
我正在运行LME,我想通过ID
(被认为是随机因子)来绘制响应变量与一个预测变量之间的关系,使另一个预测变量保持恒定。
类似地,使用iris
数据帧示例,它将与此对应:
library(nlme)
library(ggplot2)
df <- iris[,c("Sepal.Length","Sepal.Width","Petal.Length","Species")]
mod <-nlme::lme(Sepal.Length ~ Sepal.Width * Petal.Length,random= ~ 1|Species,data = df,method="REML")
如您所见,在这里species
被用作随机因子。在此示例中,我要绘制的是Sepal.Length
和Sepal.Width
之间的线性关系,并保持Petal.Length
并保持species
不变。
我已经尝试过了:
Plot <- ggplot(df,aes(x=Sepal.Width,y=Sepal.Length,colour=Species)) +
geom_point(size=1.7,alpha=0.6) +
geom_line(aes(y=predict(mod,Petal.Length=mean(iris$Petal.Length)),group=Species),size=2.1)
Plot
但是,剧情和我做的一样:
Plot <- ggplot(df,alpha=0.6) +
geom_line(aes(y=predict(mod),size=2.1)
Plot
所以,我没有保持常数Petal.Length
。我也知道我没有保持常数Petal.Length
,因为我没有为每个物种得到一条直线。也就是说,Petal.Length
的不适当之处在于使行不规则,因为当我在模型中不考虑Petal.Length
时,我会得到:
mod.b <-nlme::lme(Sepal.Length ~ Sepal.Width,method="REML")
Plot <- ggplot(df,alpha=0.6) +
geom_line(aes(y=predict(mod.b),size=2.1)
Plot
因此,有人通过随机因子为Petal.Length
模型绘制线性预测时,有谁知道如何保持一个预测变量(LME
)恒定吗?
我将不胜感激
解决方法
我认为这就是您要寻找的东西
library(ggplot2)
newdf <- df
newdf$Petal.Length <- ave(newdf$Petal.Length,newdf$Species)
ggplot(df,aes(x=Sepal.Width,y=Sepal.Length,colour=Species)) +
geom_point(size=1.7,alpha=0.6) +
geom_line(aes(y=predict(mod,newdf),group=Species),size=2.1)
https://github.com/rune1979/python_simple_password_manager
注意:
- 您以错误的方式使用了
predict
函数。您需要添加一组全新的数据,而不仅仅是一行。另外,您编写新列的方式是错误的,因为您实际上为predict
函数提供了一个名为Petal.Length
的参数,该参数属于...
,因此被忽略了。 - 我用
ave
计算了每个组的平均值,否则您的结果将毫无意义。如果您尝试以Petal.Length
的方式通过计算newiris$Petal.Length <- mean(newiris$Petal.Length)
的平均值来绘制图形,则会明白我的意思。
撰写时:
ave(newdf$Petal.Length,newdf$Species)
ave
为newdf$Petal.Length
定义的每个组计算newdf$Species
的平均值。