3

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.

Community
  • 1
  • 1
merlin2011
  • 71,677
  • 44
  • 195
  • 329

2 Answers2

4

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.

Gavin Simpson
  • 170,508
  • 25
  • 396
  • 453
1

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]])
}
Metrics
  • 15,172
  • 7
  • 54
  • 83
  • I didn't think `lapply` would print results when called in an Rscript session. (I checked to see if `Rscript -e 'z<-as.list(c("disp","cyl")) lapply(z,function(x) summary(lm(as.formula(paste("mpg",x,sep="~")),data=mtcars)))'` would return what one sees in an interactive session and it didn't. – IRTFM Oct 09 '13 at 19:09
  • What type of object would you initialise k as prior to starting the loop in order to store lm() summaries in k? – Bradford Dec 07 '19 at 16:46