[R] Interpolating variables into quoted strings

Peter Dalgaard BSA p.dalgaard at biostat.ku.dk
Wed Dec 19 23:31:46 CET 2001


William_Fitchen at oxy.com writes:

> I am new to R and am coming from a Perl background.  I have had trouble
> figuring out from the documentation how to interpolate a variable into a
> quoted string (if it's possible).  This seems to be necessary when writing a
> script that must print out strings (for example plot legends) whose content
> is calculated during the execution of the script.  
> 
> In perl I could write:
> 	
> 	$name = "John";
> 	print STDOUT "Hi $name, how's it going";
> 
> which would output the following:
> 
> 	Hi John, how's it going?
> 
> Is there a function that allows a variable containing a character string or
> numeric to be interpolated into a quoted character string?  Any help would
> be greatly appreciated!

Generally paste() or cat() is used for this:

name <- "John"
cat("Hi ", name, ", how's it going\n", sep="")

or 

out <- paste("Hi ", name, ", how's it going", sep="")
print(out)

You could also try stuff like

sub("NAME", name, "Hi, NAME, how's it going")

-- 
   O__  ---- Peter Dalgaard             Blegdamsvej 3  
  c/ /'_ --- Dept. of Biostatistics     2200 Cph. N   
 (*) \(*) -- University of Copenhagen   Denmark      Ph: (+45) 35327918
~~~~~~~~~~ - (p.dalgaard at biostat.ku.dk)             FAX: (+45) 35327907
-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-
r-help mailing list -- Read http://www.ci.tuwien.ac.at/~hornik/R/R-FAQ.html
Send "info", "help", or "[un]subscribe"
(in the "body", not the subject !)  To: r-help-request at stat.math.ethz.ch
_._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._



More information about the R-help mailing list