简体   繁体   English

使用 for 循环从多个模型中提取系数

[英]Using a for loop to extract coefficients from multiple models

I have multiple cox models (with one variable static in all models) and am trying to extract the coefficient for that variable.我有多个 cox 模型(所有模型中都有一个静态变量),并且正在尝试提取该变量的系数。

In all models the coefficient is indexed as follows: for example in model1 it is model1[[8]][1] ;在所有模型中,系数的索引如下:例如,在模型 1 中,它是模型 1[[8]][1]; for model2 it is model2[[8]][1] etc. I attempted to create a for loop but R as shown below but its not working.对于模型 2,它是模型 2[[8]][1] 等。我试图创建一个 for 循环,但 R 如下所示,但它不起作用。

Could someone help me why I am getting an error when running the following code有人可以帮助我为什么在运行以下代码时出现错误

for (i in 1:5) {
coef[i] <- exp(summary(model[i])[[8]][1])
}

I get the following error "object 'model' not found".我收到以下错误“找不到对象‘模型’”。

Many thanks in advance提前谢谢了

A一种

Here is an example of what I meant in my comment这是我在评论中的意思的一个例子

data(iris)
model1 <- lm(data = iris, Sepal.Length ~ Sepal.Width + Species)
model2 <- lm(data = iris, Sepal.Length ~ Sepal.Width)

You can do this so you don't have to type all the models.您可以这样做,这样您就不必键入所有模型。

model.list<-mget(grep("model[0-9]+$", ls(),value=T))

ls() lists all the object you have and grep() is taking all the objects that have names "model" followed by a number. ls() 列出您拥有的所有对象,而 grep() 正在获取名称为“model”的所有对象,后跟一个数字。

coefs<-lapply(model.list,function(x)coef(x)[2])
unlist(coefs)

Sepal.Width Sepal.Width 
 0.8035609  -0.2233611 

Here's a generalized example:这是一个通用示例:

model1 <- 1:5
model2 <- 2:6

I can execute a function like mean to find the average of each vector with a for loop:我可以执行一个类似于mean的函数来使用 for 循环找到每个向量的平均值:

for(i in 1:2) print(mean(get(paste0('model', i))))
#[1] 3
#[1] 4

It works.有用。 But the a more standard approach is to use the list object.但更标准的方法是使用列表对象。 Then I can execute the desired function with built-in functions like sapply :然后我可以使用内置函数(如sapply执行所需的函数:

lst <- list(model1, model2)
sapply(lst, mean)
#[1] 3 4

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM