I'm having a problem with using double quotes while formatting text strings being sent to functions in R.
在格式化发送到R中的函数的文本字符串时,我遇到使用双引号的问题。
Consider an example function code:
考虑一个示例功能代码:
foo <- function( numarg = 5, textarg = "** Default text **" ){
print (textarg)
val <- numarg^2 + numarg
return(val)
}
when running with the following input:
使用以下输入运行时:
foo( 4, "Learning R is fun!" )
The output is:
输出是:
[1] "Learning R is fun!"
[1] 20
But when I try (in various ways, as suggested here) to write "R" instead of R, I get the following outputs:
但是当我尝试(以各种方式,如此处所建议的)写“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
Using as.character(...)
or dQuote(...)
as suggested here seems to break the function because of different number of arguments.
使用as.character(...)或dQuote(...)这里建议似乎打破了函数,因为参数数量不同。
2 个解决方案
#1
1
You can try these approaches:
您可以尝试以下方法:
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!' )
#2
5
Two ways I know. First is to just use single quotes to start and end the character string:
我知道两种方式。首先是使用单引号来开始和结束字符串:
> cat( 'Learning "R" is fun!' )
Learning "R" is fun!
Second is to escape the double quotes:
第二是逃避双引号:
> cat( "Learning \"R\" is fun!" )
Learning "R" is fun!
Note that this works because I use cat
, which is intended to output strings to the console. It seems you use print()
which shows the object rather than output it
请注意,这是有效的,因为我使用cat,它旨在将字符串输出到控制台。看来你使用print()来显示对象而不是输出它
#1
1
You can try these approaches:
您可以尝试以下方法:
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!' )
#2
5
Two ways I know. First is to just use single quotes to start and end the character string:
我知道两种方式。首先是使用单引号来开始和结束字符串:
> cat( 'Learning "R" is fun!' )
Learning "R" is fun!
Second is to escape the double quotes:
第二是逃避双引号:
> cat( "Learning \"R\" is fun!" )
Learning "R" is fun!
Note that this works because I use cat
, which is intended to output strings to the console. It seems you use print()
which shows the object rather than output it
请注意,这是有效的,因为我使用cat,它旨在将字符串输出到控制台。看来你使用print()来显示对象而不是输出它