发送包含双引号的文本字符串

时间:2012-11-19 07:17:15

标签: r string-formatting double-quotes output

在格式化发送到R中的函数的文本字符串时,我遇到使用双引号的问题。

考虑一个示例功能代码:

foo <- function( numarg = 5, textarg = "** Default text **" ){ 
    print (textarg)
    val <- numarg^2 + numarg
    return(val) 
}

使用以下输入运行时:

foo( 4, "Learning R is fun!" )

输出结果为:

[1] "Learning R is fun!"
[1] 20

但是当我尝试(以各种方式,如建议的here)来写“R”而不是R时,我得到以下输出:

> foo( 4, "Learning R is fun!" )
[1] "Learning R is fun!"
[1] 20
> foo( 4, "Learning "R" is fun!" )
Error: unexpected symbol in "funfun( 4, "Learning "R"
> foo( 4, "Learning \"R\" is fun!" )
[1] "Learning \"R\" is fun!"
[1] 20
> foo( 4, 'Learning "R" is fun!' )
[1] "Learning \"R\" is fun!"
[1] 20

根据建议here使用as.character(...)dQuote(...)似乎会因为参数数量不同而破坏功能。

2 个答案:

答案 0 :(得分:5)

我知道两种方式。首先是使用单引号来开始和结束字符串:

> cat( 'Learning "R" is fun!' )
Learning "R" is fun!

其次是逃避双引号:

> cat( "Learning \"R\" is fun!" )
Learning "R" is fun!

请注意,这是有效的,因为我使用cat,用于将字符串输出到控制台。您似乎使用print()来显示对象而不是输出它

答案 1 :(得分:1)

您可以尝试以下方法:

foo <- function(numarg = 5, textarg = "** Default text **" ){ 
    cat(c(textarg, "\n")) 
    val <- (numarg^2) + numarg
    return(val) 
}

foo <- function(numarg = 5, textarg = "** Default text **" ){ 
    print(noquote(textarg)) 
    val <- (numarg^2) + numarg
    return(val) 
}

foo( 4, "Learning R is fun!" )
foo( 4, 'Learning "R" is fun!' )