5

在格式化发送到 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

但是,当我尝试(以各种方式,如此处所建议)写“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

由于参数数量不同,使用as.character(...)or在这里dQuote(...)建议似乎会破坏函数。

4

2 回答 2

5

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

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

其次是转义双引号:

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

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

于 2012-11-19T07:31:16.127 回答
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!' )
于 2012-11-19T07:33:56.277 回答