I would like to build some plotmath
expressions and some string programmatically. The expressions and strings (in other words, the desired output) are
k[xy[2]]
k[xy[5]]
k[xy[7]]
k[xy[9]]
k[xy[11]]
k[xy[13]]
K[xx[2]]
K[xx[5]]
K[xx[7]]
K[xx[9]]
K[xx[11]]
K[xx[13]]
C[xx[2]]
C[xx[5]]
C[xx[7]]
C[xx[9]]
C[xx[11]]
C[xx[13]]
"k_xy_2"
"k_xy_5"
"k_xy_7"
"k_xy_9"
"k_xy_11"
"k_xy_13"
"Kxx_2"
"Kxx_5"
"Kxx_7"
"Kxx_9"
"Kxx_11"
"Kxx_13"
"Cxx_2"
"Cxx_5"
"Cxx_7"
"Cxx_9"
"Cxx_11"
"Cxx_13"
You see they're quite a lot, so instead than hard-coding them (and repeat many lines of code, against the DRY directive) I'd rather build them programmatically. Building the strings is easy (but if you have a better/faster idea, I'm all ears):
for (i in c(2,5,7,9,11,13)) {
for (var in c("k_xy", "Kxx", "Cxx")) {
print(paste0(var,i))
}
}
However, how do I build the plotmath
expressions? I thought of using bquote
, but it's giving me an headache:
for (i in c(2,5,7,9,11,13)) {
for (var in list(c("k_","xy"), c("K","xx"), c("C","xx"))) {
print(paste0(var[1],var[2],i))
print(bquote(.(var[1])[.(var[2])[.(i)]]))
}
}
Output:
[1] "k_xy2"
"k_"["xy"[2]]
[1] "Kxx2"
"K"["xx"[2]]
[1] "Cxx2"
"C"["xx"[2]]
[1] "k_xy5"
"k_"["xy"[5]]
[1] "Kxx5"
"K"["xx"[5]]
[1] "Cxx5"
"C"["xx"[5]]
[1] "k_xy7"
"k_"["xy"[7]]
[1] "Kxx7"
"K"["xx"[7]]
[1] "Cxx7"
"C"["xx"[7]]
[1] "k_xy9"
"k_"["xy"[9]]
[1] "Kxx9"
"K"["xx"[9]]
[1] "Cxx9"
"C"["xx"[9]]
[1] "k_xy11"
"k_"["xy"[11]]
[1] "Kxx11"
"K"["xx"[11]]
[1] "Cxx11"
"C"["xx"[11]]
[1] "k_xy13"
"k_"["xy"[13]]
[1] "Kxx13"
"K"["xx"[13]]
[1] "Cxx13"
"C"["xx"[13]]
Not what I wanted, clearly. Any better idea? PS don't feel forced to follow my ugly code, only thing I care about is the output.
EDIT I was suggested to just parse the strings, but I'm not sure what it means. I need the plotmath
to build labels for my plots: the strings are not good for this, but they're good to build the names of the files where I save the plots (so this is why I need both plotmath
expressions AND strings). Example: this is fine
plot(0, xlab = expression(k[xy[13]]))
But this is not:
plot(0, xlab = expression("k_xy_13"))