【问题标题】:How to print variables inside quotes in message()如何在消息()中的引号内打印变量
【发布时间】:2012-06-24 16:23:39
【问题描述】:

我有以下变量:

min.v<-5
max.v<-10

我想发以下消息

Test this. You entered "5 10" 

这可以用message()paste() 打印吗,因为这两个函数都将引号视为字符串。 消息中的变量应该在双引号内

我试过message(as.character(paste(min.v, " ",max.v))),但双引号被忽略了。

这个问题可能和这个Solve the Double qoutes within double quotes issue in R正好相反

【问题讨论】:

  • pastemessage “将引号视为字符串”并不是说 R 解释器将引号视为指定对象名称。

标签: r


【解决方案1】:

你有两个三个选项

选项 1:转义引号。为此,您必须使用\"

cat("You entered ", "\"", min.v, " ", max.v,"\"", sep="")
You entered "5 10"

选项 2:将双引号嵌入单引号中:

cat("You entered ", '"', min.v, " ", max.v,'"', sep="")
You entered "5 10"

编辑: 感谢@baptiste,努力使这个答案更全面

选项3:使用函数dQuote()

options(useFancyQuotes=FALSE)
cat("You entered ", dQuote(paste(min.v, max.v)), sep="")
You entered "5 10"

【讨论】:

    【解决方案2】:
    x = 5; y = "indeed"
    message("you entered ", dQuote(x))
    message("you entered ", dQuote(paste(x, y)))
    

    【讨论】:

    • @G看你需要先连接它们
    【解决方案3】:

    虽然sprintf 可能会变得相当复杂,但我发现代码通常比大多数其他选项更简洁。从本质上讲,您有一条消息要在要插入变量值的位置进行格式化——这就是 sprintf 的用途:

    min.v <- 5
    max.v <- 10
    msg <- 'Test this. You entered "%i %i"\n'
    str <- sprintf(msg, min.v, max.v) #generates string
    cat(str) #to output
    # or message(str)
    

    %i 是需要整数值的占位符,有关详细信息,请参阅?sprintf。尽管此解决方案仍然依赖于用单引号括起双引号,但您获得的代码比直接使用 pastecat 时更具可读性。

    【讨论】:

      猜你喜欢
      • 2015-03-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-07-02
      • 2011-06-19
      相关资源
      最近更新 更多