Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
396 views
in Technique[技术] by (71.8m points)

r - Send a text string containing double quotes to function

I'm having a problem with using double quotes while formatting text strings being sent to functions in 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:

> 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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...