簡體   English   中英

有沒有辦法在 R 中使用 lme() function 創建具有隨機效應的二次回歸?

[英]Is there a way to create a quadratic regression with random effect with lme() function in R?

我試圖在 R 中創建一個圖表來描述具有隨機效應的二次項。

我使用具有隨機效果的 function lme(),其中包括隨機斜率和截距:

    diversity = c(0.69, 1.54, 0.84, 1.48, 1.71, 1.80, 2.09, 1.63, 2.40, 2.20, 
        2.56, 2.30, 2.67, 1.98, 1.65, 2.33, 2.17, 1.98, 1.96, 1.33, 2.55, 2.49, 2.39, 2.47, 2.42, 2.44, 2.35, 2.33, 2.01, 2.39)
    Plot_age = c(7, 7, 9, 12, 17, 19, 22, 32, 31, 35, 35, 36, 36, 36, 37, 37,
 37, 38, 38, 38, 110, 111, 112, 113, 115, 116, 117, 118, 120, 121)
    subject = c("A", "B", "C", "A", "B", "C", "A", "B", "C", "A", "B", "C", "A", "B", "C", "A", "B", "C", "A", "B", "C", "A", "B", "C", "A", "B", "C", "A", "B", "C")

此數據框僅向您提供我的實際數據的概覽。 我希望它無論如何都會起作用。

age <- Plot_age
div <- diversity
age2 <- Plot_age^2
qm1r <- lme( fixed = div ~ age+age2, 
             random = ~ age |subject)

為了獲得圖表,我像往常一樣使用 plot() function。 使用 lm() 它起作用了,現在我還使用了 predict() function 和 lme() 以及以下術語:

plot(age, div, pch = 16)

X <- seq(0, 200, 0.1) #X 的范圍是 0 到 200,其中包括我所有的 x 軸數據

NewData <- data.frame(age= Plot_age,
                      age2 = Plot_age^2,
                      subject = subject)

Y <- predict(qm1r, NewData)

points(Y ~ X, type ="l", lwd=3)

我得到了我的點的圖形表示()function。不幸的是它沒有正確顯示(我想要二次拋物線,沒有非線性線)-->見下圖

xmax <- X[Y == max(Y)] 

#我使用這個function的原因是根據二次拋物線圖的峰值獲得xmax(這在我只使用lm()function時有效,lme()不起作用)有沒有辦法創建圖形用隨機效應表示我的 lme() function? 如果有人能解決這個問題,我會很高興 :) 我得到了一個圖表,但沒有從點中進行二次回歸()function enter image description here

## put your data in a data frame
df = data.frame(diversity, Plot_age, subject)    

## define the model using the data frame data
## note the `I()` which lets us square a variable in the formula
## so we can skip the step of creating a vector of squared values
library(nlme)
qm1r <- lme( fixed = diversity ~ Plot_age + I(Plot_age^2), 
             random = ~ Plot_age | subject,
             data = df)

## make the initial plot, again using data in the data frame
with(df, plot(Plot_age, diversity, pch = 16))

## create data for prediction, also in a data frame
## Use the same column name as original data so the model knows what to do!
## 201 points is plenty, setting `by = 0.1` to get 2001 points isn't necessary
pred_data = data.frame(
  Plot_age = seq(0, 200)
)

## add predictions to the pred_data data frame
## level = 0 is population-level
pred_data$diversity = predict(qm1r, newdata = pred_data, level = 0)

## add the predicted line to the plot
with(pred_data, lines(Plot_age, diversity))

在此處輸入圖像描述

如果您希望 x 軸一直到 go 到 200,請在初始plot()調用中設置xlim = c(0, 200)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM