merlin2011
merlin2011

Reputation: 75599

How can I get the output of the summary() command if it is called within a loop?

Suppose Z is a vector of feature names.

How can I get the summary command in the following Rscript to actually print?

for (var in Z)                
{                             
#cat(i)                       
form = paste('crim ~', var)   
lm.fit=lm(form, data=Boston)  
summary(lm.fit)               
}                             

If I type summary(lm.fit) at the R prompt, it works, but when I source the Rscript which contains this loop, I get no output. I have already tried the solution How can I run an 'R' script without suppressing output? but it does not cause summary to print.

Upvotes: 4

Views: 15360

Answers (2)

Gavin Simpson
Gavin Simpson

Reputation: 174928

summary() is supposed to return a object of class "summary.foo" assuming that the summary.foo() method was called. Then a print() method for that class, print.summary.foo() is supposed to print the object returned by summary.foo().

Automatic printing is turned off in for () loops (and some other circumstances. You need an explicit call to print(). When you call summary(bar) at the prompt, you are effectively doing print(summary(bar)). It is that addition of the print() call that is suppressed in for () loops.

Hence, write

print(summary(lm.fit))

in your loop and you'll see the output.

Upvotes: 5

Metrics
Metrics

Reputation: 15458

You can get rid of for loop using lapply.

z<-as.list(c("disp","cyl"))
nn<-lapply(z,function(x) summary(lm(as.formula(paste("mpg",x,sep="~")),data=mtcars)))
print(nn) # or show(nn)

If you want to stick to for loop here is the solution:

for (i in z){

    k[[i]]<-summary(lm(as.formula(paste("mpg",z[i],sep="~")),data=mtcars))
    print(k[[i]])
}

Upvotes: 2

Related Questions