jeudi 28 mars 2019

How to use an if/else statement to plot different colored lines within a plotting for-loop (in R)

I created a for loop to plot 38 lines (which are the rows of my matrix, results.summary.evap, and correspond to 38 total samples). I'd like to make these lines different colors, based on a characteristic pertaining to each sample: age. I can access the age in my input matrix: surp.data$Age_ka.

However, the matrix I am looping over (results.summary.evap) does not have sample age or sample name, though each sample should be located in the same rows for both surp.data and results.summary.evap.

Here is the for loop I created to plot 38 lines, one corresponding to each sample. In this case, results.summary.evap is what I am plotting from, and this matrix is derived from information in the surp.data input file.

par(mfrow=c(3,1)) 
par(mar=c(3, 4, 2, 0.5))
plot(NA,NA,xlim=c(0,10),ylim=c(0,2500), ylab = "Evaporation (mm/yr)", xlab = "Relative Humidity")
for(i in 1:range){
  lines(rh.sens,results.summary.evap[i,])
}
```


I'd like to plot lines in different colors based on the age associated with each sample. I tried to incorporate an if/else statement into the loop, that would plot in a different color if the corresponding sample age was greater that 20 in the input file. 


```
for(i in 1:range){
  if surp.data$Age_ka[i]>20 {
lines(rh.sens,results.summary.evap[i,], col = 'red')
} else {
  lines(rh.sens,results.summary.evap[i,], col = 'black')
  }
}

This for loop won't run (due to issues with parentheses). I'm not sure if what I am doing if fundamentally wrong, or if i've just missed a parenthesis somewhere. I'm also not sure how to make this a bit more robust; for example, by plotting in 6-8 different colors based on age ranges, rather than just two.

Thank you!

Aucun commentaire:

Enregistrer un commentaire