![](/img/trans.png)
[英]How to test a linear regression model slope to the identity line slope in R
[英]Adding a slope(s) line to a linear model(s) that's in a loop in R
抱歉,如果這沒有任何意義,這是我第一次使用 R(和一般編碼),我迷路了。 任何幫助將不勝感激。
我有來自不同國家和年份的麻疹病例數數據集。
到目前為止,我有(我假設正確但不完全確定):
將該數據集子集化為僅包含 1998 年之后(至 2018 年)的信息,稱為 All_after
使用循環(1-194 是不同的國家),運行該時間段內年份對自然對數的影響的線性模型
我應該得到的是線性模型中每個國家/地區的斜率(然后我可以將其繪制為直方圖)。 但是,使用我當前的代碼,我是“無斜率”的。 我已經在循環內外嘗試了 abline 函數和 lm 函數,但得到的答案是我放在括號中的任何東西都不是有限的。
到目前為止,這是我的代碼:
All_after <- subset(Measles, year >= 1998, year < 2018)
attach(All_after)
All_after$Cname <- "1":"194"
log_All_after <- log(All_after[,7]+1)
i <- c(Cname="1":"194")
for (val in i) {
with(All_after[All_after$Cname==1,] plot(year,log_All_after))
model5 <- lm(log_All_after~year, data=All_after, subset=i)
}
如果這都是胡言亂語,再次道歉!
編輯:
使用 summary 函數,這是 All_after 出現的內容:
> summary(All_after)
X WHO_REGION ISO_CODE Cname
Min. :3493 AFR : 987 AFG : 21 Afghanistan : 21
1st Qu.:4511 AMR : 735 AGO : 21 Albania : 21
Median :5530 EMR : 441 ALB : 21 Algeria : 21
Mean :5530 EUR :1113 AND : 21 Andorra : 21
3rd Qu.:6548 SEAR: 231 ARE : 21 Angola : 21
Max. :7566 WPR : 567 ARG : 21 Antigua and Barbuda: 21
(Other):3948 (Other) :3948
Disease year cases
measles:4074 Min. :1998 Min. : 0.0
1st Qu.:2003 1st Qu.: 0.0
Median :2008 Median : 20.5
Mean :2008 Mean : 2402.6
3rd Qu.:2013 3rd Qu.: 446.5
Max. :2018 Max. :217151.0
NA's :294
我在下面寫的內容可以幫助您入門。 我大致猜測你的數據是什么樣的,並模擬了 3 個國家的一些值:
n = 21
All_after <- data.frame(
X = sample(3000:4000,n*3),
WHO_REGION = rep(c("EMR","EUR","EUR"),each=n),
ISO_CODE = rep(c("AFG","AND","ALB"),each=n),
Cname = rep(c("Afghanistan","Andorra","Albania"),each=n),
Disease="measles",
year = sample(1998:2018,n*3,replace=TRUE),
cases = rnbinom(n*3,mu=400,size=0.1)
)
我們確實按照您在第 7 列中的記錄進行記錄。 我將它添加到 data.frame
All_after$log_All_after <- log(All_after[,7]+1)
以下是我進行更改的部分,您需要創建一個唯一的國家名稱向量以進行迭代,以及一個用於存儲結果的列表:
# create a vector of all your countries to iterate through
all_countries <- unique(All_after$Cname)
# to store the output
output <- vector("list",length(all_countries))
names(output) <- all_countries
在這里,我使用par(mfrow=c(1,3))
每頁繪制 3 個圖,如果您更喜歡每頁一個圖,可以刪除它。 關鍵是將您的繪圖存儲在 pdf 中,這樣它就不會丟失。
pdf("regress.pdf",width=12,height=8)
par(mfrow=c(1,3))
for (val in all_countries) {
# you need to subset using Cname == val
countryData <- All_after[All_after$Cname==val,]
with(countryData, plot(year,log_All_after,main=val))
model5 <- lm(log_All_after~year, data=countryData)
abline(model5,lty=8,col="blue")
output[[val]] <- coefficients(model5)
}
dev.off()
你可以收集所有的結果
do.call(rbind,output)
(Intercept) year
Afghanistan -202.79141 0.10199578
Andorra -41.21576 0.02161816
Albania 115.88641 -0.05598124
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.