![](/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.