[R] Simple plot loop

Jim Lemon jim at bitwrit.com.au
Fri May 4 09:24:09 CEST 2012


On 05/04/2012 12:04 AM, Ben Neal wrote:
> Jim, thanks for the reply. I tried what you recommend, but I still get an error when running it, just as I did with the similar loops I was trying. Here is the error:
>
> Error in xy.coords(x, y) : 'x' and 'y' lengths differ
>
> That comes from this code:
>
> #Get file
> library(zoo)
> setwd("/Users/benjaminneal/Documents/All Panama/1110_Panama/CNAT_Segmenting")
> Data = read.csv("120503_CNAT_Summary.csv", header=T)
>
> #fill in missing data from last observation
> Data2<- na.locf(Data)
> attach(Data2)
>
> #Plot line, and make it loop
> for(column in names(Data2)[2:length(Data2)])
>    lines(MONTH,column,type="o",pch=22,lty=2,col="blue")
> ------------------------------------------------
> The problem perhaps is in my data. My columns are observations over time, column headers are individual names, and the first column is the time series in months. An example is here:
> MONTH   Tag101
> 0             234
> 2             236
> 4             239
> 8             300
> 10           320
>
> This then repeats for different individuals . . . I think my problem must be that my length of MONTH is different than my length of observations of each column . . . except that it is not, as far as I can tell! Thank you for assisting me with this simple but frustrating problem - I have the greatest respect for those of you who provide these answers that so many of us read and utilize. Thank you. Ben Neal

Hi Ben,
Okay, we're going to have to fake it.

Data2<-data.frame(MONTH=seq(0,10,by=2),
  TAG01=sample(200:400,6),TAG02=sample(200:400,6),
  TAG03=sample(200:400,6),TAG04=sample(200:400,6))
column_names<-names(Data2)
attach(Data2)
colorvec<-c("red","green","green","blue")
plot(MONTH,TAG01,ylim=c(200,400),type="o",col=colorvec[1])
for(column in 2:(length(Data2)-1))
  lines(MONTH,get(column_names[column+1]),
   type="o",col=colorvec[column])

I wasn't being careful enough. You have to use get() when passing the 
character string that is the name of the column. Always something else 
to learn.

Jim



More information about the R-help mailing list