使用 bquote 或其他命令以编程方式构建 plotmath 表达式和字符串

build plotmath expressions and strings programmatically using bquote or other commands

我想以编程方式构建一些 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 指令),我宁愿以编程方式构建它们。构建字符串很容易(但如果您有 better/faster 想法,我会洗耳恭听):

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 不要被迫遵循我丑陋的代码,我唯一关心的是输出。

EDIT 有人建议我只解析字符串,但我不确定这意味着什么。我需要 plotmath 来为我的地块建立标签:字符串不适合这个,但它们很好地建立我保存地块的文件的名称(所以这就是为什么我需要两者 plotmath 表达式 AND 字符串)。示例:这很好

plot(0, xlab = expression(k[xy[13]]))

但这不是:

plot(0, xlab = expression("k_xy_13"))

构建表达向量:

expr <- vector(length = 3, mode = "expression")
expr[[1]] <- quote(k[xy[.(i)]])
expr[[2]] <- quote(K[xx[.(i)]])
expr[[3]] <- quote(C[xx[.(i)]])

人数指标:

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"