In R I would like to create several plots in a for-loop. The y-axis label is supposed to exhibit a subscript, in which the subscript text should vary along with the loop-iterator.
For subscripting a label, I previously used "expression". However, as you can see in the minimal example, the subscript in the expression cannot be indexed the way I thought it would (instead of printing "1", "2", "3" it simply prints "i"). Do you have an idea on how to fix this (either by using the expression function or any other text function able to produce subscripts)?
Minimal code:
# minimal example code
Data = matrix(ncol = 4, nrow = 1000)
colnames(Data) = c("time", "k1", "k2", "k3")
Data[,1] = seq(0.1,100,0.1)
Data[,2] = sin(Data[,1])
Data[,3] = cos(Data[,1])
Data[,4] = tan(Data[,1])
for(i in 1:3) {
plot(Data[,1], Data[,(1+i)], type = "l", lwd = 2, xlab = "time", ylab = expression("k" [i]))
}
Thank you!
Use bquote
. Stolen from this SO:
Subscripts in plots in R
for(i in 1:3) {
plot(Data[,1], Data[,(1+i)], type = "l", lwd = 2, xlab = "time", ylab = bquote(k[.(i)]))
}
It has very strange syntax of: bquote(WORD [ . (OBJECT) ]
. Note that WORD
is not quoted and the dot. I believe the .
is referring to what environment to go find OBJECT
.