簡體   English   中英

按類別擬合二次模型並估計 R 中的拐點

[英]Fit quadratic model by categories and estimate inflection point in R

我想問你一個問題。 我有興趣按類別擬合二階多項式回歸,然后計算每個回歸和類別的拐點。

變量 y 為 C3,數值回歸變量 (x) 為 C2,類別為 C1。

我使用的數據庫和代碼如下。 非常感謝您,任何幫助我都會非常感謝您!

df <- data.frame(C1=c('A','A','A','A','B','B','B','B'),
         C2=c('1','2','3','4','2','4','5','6'),
         C3=c(10,20,25,15,20,60,60,20),
         stringsAsFactors = FALSE)
df$C2<-as.numeric(df$C2)
df$C3<-as.numeric(df$C3)

model<-lm(C3~C1+(poly(C2,degree=2,raw=TRUE))+C1*(poly(C2,degree=2,raw=TRUE)), data = df)

在此處輸入圖片說明

首先讓我們看看方程的一階導數:

在此處輸入圖片說明

C1B=0並且您將其設置為零並求解時,您會得到以下結果:

在此處輸入圖片說明

因此,一階導數是線性項系數的負數除以平方項系數的兩倍。 我們可以使用它來識別 R 中的相同數量。

## get the coefficients from the model
b <- coef(model)

## find the ones that end with 1 (these are the coefficients on the linear term)
b1 <- b[grep("1$", names(b))]
## find the ones that end with 2 (these are the coefficients on the squared term)
b2 <- b[grep("2$", names(b))]
## put the two terms in a matrix
bmat <- cbind(b1, b2)

現在,非參考組的系數是全局系數加上該特定組的系數。 因此,全局系數是對參考組的影響。

## coefficients for the reference group. 
comb.b <- bmat[1,]
for(i in 2:nrow(bmat)){
  ## make the coefficients for the non-reference groups
  comb.b <- rbind(comb.b, bmat[1,] + bmat[i,])
}
## calculate the inflection point
inf.point <- -comb.b[,1]/(2*comb.b[,2])
## attach category names
names(inf.point) <- levels(df$C1)
inf.point
#          A          B 
# 2.700000 4.033333 



暫無
暫無

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

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