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

Kha*_*mes 5 r string-formatting double-quotes output

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

考虑一个示例功能代码:

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

使用以下输入运行时:

foo( 4, "Learning R is fun!" )
Run Code Online (Sandbox Code Playgroud)

输出是:

[1] "Learning R is fun!"
[1] 20
Run Code Online (Sandbox Code Playgroud)

但是,当我尝试(以各种方式,如此处所示)写"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
Run Code Online (Sandbox Code Playgroud)

使用as.character(...)dQuote(...)作为建议在这里似乎打破,因为不同数量的参数的函数.

Sac*_*amp 5

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

> cat( 'Learning "R" is fun!' )
Learning "R" is fun!
Run Code Online (Sandbox Code Playgroud)

第二是逃避双引号:

> cat( "Learning \"R\" is fun!" )
Learning "R" is fun!
Run Code Online (Sandbox Code Playgroud)

请注意,这是因为我使用cat,它用于将字符串输出到控制台.看来你用print()它来显示对象而不是输出它

  • 当我在发送文本功能时尝试使用`cat`时,文本格式正确(使用你的任何建议),只有这次,它输出`学习'R"很有趣!NULL`而不是`Learning"R"很有趣!` 知道如何终止"NULL"添加吗?(更重要的是,任何想法来自哪里?) (3认同)

Tyl*_*ker 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!' )
Run Code Online (Sandbox Code Playgroud)