-1

I have multiple cox models (with one variable static in all models) and am trying to extract the coefficient for that variable.

In all models the coefficient is indexed as follows: for example in model1 it is model1[[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.

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

user3919790
  • 557
  • 1
  • 4
  • 10
  • You should provide a [reproducible example](http://stackoverflow.com/questions/5963269/how-to-make-a-great-r-reproducible-example). The error message implies that there is no variable named "model" defined. Please include enough context and sample input data so we can see that's not the case. Did you create a bunch of different variables? Are you models not stored in a list? – MrFlick Jul 01 '15 at 19:08
  • model[i] is not the same as modeli, i.e model[1] isn't model1, so r is looking for an object called "model" and trying to get its i-th element. Try creating a list with all your models – Andrelrms Jul 01 '15 at 19:10
  • As Andrelrms mentioned you should use lists. But if you don't know them well enough, `exp(summary(get(paste0('model', i)))[[8]][1])` might get you there. – Pierre L Jul 01 '15 at 19:15

2 Answers2

2

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.

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

Sepal.Width Sepal.Width 
 0.8035609  -0.2233611 
Andrelrms
  • 819
  • 9
  • 13
  • 1
    Hi Andrelrms - that is exactly what i was trying to do thanks! One additional quick question - suppose i have 200 models, how can i combine all them as a list from model1 to model200...would i have to type each one out? – user3919790 Jul 01 '15 at 19:29
  • I edited the code so you don't have to type everything yourself – Andrelrms Jul 01 '15 at 19:44
0

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:

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:

lst <- list(model1, model2)
sapply(lst, mean)
#[1] 3 4
Pierre L
  • 28,203
  • 6
  • 47
  • 69