# [R] simple linear plots with a loop

Jim Lemon jim at bitwrit.com.au
Mon Apr 7 04:00:46 CEST 2014

```On 04/07/2014 11:07 AM, Kristi Glover wrote:
> Hi R users,
> I was trying to plot with  a fixed y with many independet variables. I tried this loop but it did not work. any suggestions? I wanted to make 9 plots. This is a just an example data.
>
> dat1<- as.data.frame(matrix(sample(1:20,100,replace=TRUE),ncol=10))
> lapply(seq_len(ncol(dat1)),function(i)
> {
> par(mfrow=c(3,3)),
> plot(dat1[,1],dat1[,i+1],
> z[,i]<-lm(dat1[,1]~dat1[,i+1]),
> abline(z),
> summary(z[,i])
> }
>   here first column is dependent variable and other V2 to V10s are independent variables. Also wanted look the summary (linear model) with each variable.
> KG

Hi Kristi,
You can get your plots like this:

for(i in 2:10) {
plot(dat1[,1],dat1[,i],ylab=paste("dat1[,",i,"]",sep=""))
z<-lm(dat1[,1]~dat1[,i])
abline(z)
print(summary(z))
}

This prints the summaries on the console. If you want to get a listing
with plots and summaries together, there are a number of ways, one of
which is the htmlize function in the prettyR package. Save the following
to a file named kg.R:

#title~Example listing with htmlize
z[[1]]<-NULL
png("kg.png",width=600,height=600)
par(mfrow=c(3,3))
for(i in 2:10) {
plot(dat1[,1],dat1[,i],ylab=paste("dat1[,",i,"]",sep=""))
z[[i]]<-lm(dat1[,1]~dat1[,i])
abline(z[[i]])
}
dev.off()
for(i in 1:9) print(summary(z[[i]]))

then:

library(prettyR)
htmlize("kg.R")

Jim

```