【问题标题】:In R, how can a string function argument be expanded to mathematical symbols using plotmath?在 R 中,如何使用 plotmath 将字符串函数参数扩展为数学符号?
【发布时间】:2018-12-17 18:27:12
【问题描述】:

这是一个例子:

   PMEx <- function(t) {
   y <- (1:10)^2
   plot(1:10,y,type="l")
   text(2,90,label="This is NOT what I want -->",adj=0)
   text(2,80,label="This IS what I want -->",adj=0)
   text(2,70,label="This is NOT what I want -->",adj=0)  
   #  --- These are representative lines of code --- 
   text(5,90,label=expression("x[0]"))  # This is NOT what I want 
   text(5,80,label=expression(x[0]))    # This IS what I want
   text(5,70,label=expression(t))       # This is NOT what I want  
} # End of PMEx().  
RunPMEx <- function() { 
   PMEx("x[0]") 
} # End of RunPMEx().  
RunPMEx()

此代码生成一个带有文本行的图,一个显示我想要的内容(下标为 0 的字母 x),另外两个显示使用 expression() 时会发生什么(不是我想要的)。我在 Stack Overflow 中尝试了各种建议,但在这种情况下它们都不起作用(例如,使用 bquote(.(t))、粘贴、解析、替换)。 PMEx(t) 的最后 text(...) 行是我想要的原型。

【问题讨论】:

    标签: r expression plotmath


    【解决方案1】:

    您必须将该字符串解析为表达式。使用

    text(5,70,label=parse(text=t)) 
    

    例如

    test <- function(t) {
        plot(0:1, 0:1)
        text(.5, .5, label =parse(text=t))
    }
    test("x[0]")
    

    或者你可以传入一个带引号的表达式而不是一个字符串

    test2 <- function(q) {
        plot(0:1, 0:1)
        text(.5, .5, label=q)
    }
    test2(quote(x[0]))
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-08-17
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-01-25
      相关资源
      最近更新 更多