我想以编程方式构建一些plotmath
表达式和一些字符串。表达式和字符串(换句话说,所需的输出)是
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"
你看到它们相当多,所以不是硬编码(而是重复多行代码,反对DRY指令),我宁愿以编程方式构建它们。建立字符串很容易(但如果你有更好/更快的想法,我会全力以赴):
for (i in c(2,5,7,9,11,13)) {
for (var in c("k_xy", "Kxx", "Cxx")) {
print(paste0(var,i))
}
}
但是,如何构建plotmath
表达式?我想过使用bquote
,但这让我很头疼:
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)]]))
}
}
输出:
[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]]
显然不是我想要的。有什么好主意吗? PS并不觉得被迫遵循我丑陋的代码,只有我关心的是输出。
编辑我被建议只是解析字符串,但我不确定它是什么意思。我需要plotmath
为我的情节构建标签:字符串对此不好,但是它们很好地构建了我保存图形的文件的名称(所以这就是为什么我需要两个{{ 1}}表达式 AND 字符串)。示例:这很好
plotmath
但这不是:
plot(0, xlab = expression(k[xy[13]]))
答案 0 :(得分:1)
构建表达式向量:
nums <- c(2,5,7,9,11,13)
数字索引:
bquote
循环以应用do.call
。我们使用一些plotexpr <- mapply(function(e, i) do.call(bquote, list(e)),
rep(expr, each = length(nums)), nums)
魔法来代替表达式:
plot.new()
plot.window(c(0.4, 0.6), c(-0.5, 0.5))
for (i in seq_along(plotexpr))
text(0.5, -0.5 + 0.05 * i, plotexpr[[i]])
显示结果:
do.call(paste0,
expand.grid(c(2,5,7,9,11,13), c("k_xy_", "Kxx_", "Cxx_"))[, 2:1])
#[1] "k_xy_2" "k_xy_5" "k_xy_7" "k_xy_9" "k_xy_11" "k_xy_13" "Kxx_2" "Kxx_5"
#[9] "Kxx_7" "Kxx_9" "Kxx_11" "Kxx_13" "Cxx_2" "Cxx_5" "Cxx_7" "Cxx_9"
#[17] "Cxx_11" "Cxx_13"
用于创建字符串的高效矢量化方式:
{{1}}