[R] Turning a Variable into String

Phil Spector spector at stat.berkeley.edu
Mon Dec 20 01:30:38 CET 2010


Paolo -
   One way to make the function do what you want is to replace 
the line

  print(sprintf("OK with %s and %s\n", var1, var2))

with

  cat('OK with',substitute(var1),'and',substitute(var2),'\n')

With sprintf, you'd need

  print(sprintf("OK with %s and %s\n", deparse(substitute(var1)), deparse(substitute(var2))))

but since you're just printing the string returned by sprintf, I'd
go with cat.

 					- Phil Spector
 					 Statistical Computing Facility
 					 Department of Statistics
 					 UC Berkeley
 					 spector at stat.berkeley.edu


On Mon, 20 Dec 2010, Paolo Rossi wrote:

> I would like to know how to turn a variable into a string. I have tried
> as.symbol and as.name but it doesnt work for what I'd like to do
>
> Essentially, I'd like to feed the function below with two variables. This
> works fine in the bit working out number of elements in each variable.
>
> In the print(sprintf("OK with %s and %s\n", var1, var2))  line I would like
> var1 and var2 to be magically substituted with a string containing the name
> of var1 and name of var2.
>
> Thanks in advance
>
> Paolo
>
>
>
> haveSameLength <- function(var1, var2) {
> if (length(var1)==length(var2))
>  {
>   print(sprintf("OK with %s and %s\n", var1, var2))
> } else {
>   print("Problems!!")
> }
> }
>
> 	[[alternative HTML version deleted]]
>
> ______________________________________________
> R-help at r-project.org mailing list
> https://stat.ethz.ch/mailman/listinfo/r-help
> PLEASE do read the posting guide http://www.R-project.org/posting-guide.html
> and provide commented, minimal, self-contained, reproducible code.
>



More information about the R-help mailing list