5

I have a data frame with 36 columns and more than 3000 rows. I am using plot function inside a for loop to plot graphs of each column. I want the title of the graph to appear as column name. How can I do that?

for(i in c(1:36)){
  plot(DowData[,i],type="l",main="colnames(DowData)[i]")
}
lmo
  • 37,904
  • 9
  • 56
  • 69
Ved Gupta
  • 183
  • 3
  • 15
  • I guess you mean "column name as title", "not title as column name" ... Then your code is correct except that you need to erase the parenthesis in the main argument. You don't want to pass the expression `colnames(DowData)[i]`as as string (which you do) but the result of this expression, i.e. the name of the column. So just `colnames(DowData)[i]` without parenthesis. – Mark Heckmann Jan 02 '14 at 11:12
  • @MarkHeckmann Yes, this also worked. I guess I should have played a little with my code. Thanks a lot. – Ved Gupta Jan 02 '14 at 11:17

2 Answers2

7

Using lapply you can loop over columns names:

 invisible(lapply(colnames(DowData),function(x){
      plot(DowData[,x],main=x,type="l")
    }))
agstudy
  • 119,832
  • 17
  • 199
  • 261
1
data <- read.csv("sample.csv",header=T,sep=",")
for ( i in seq(1,length( data ),1) ) plot(data[,i],ylab=names(data[i]),type="l")

This should Work

Prasanna Nandakumar
  • 4,295
  • 34
  • 63