[R] Turning a Variable into String

Duncan Murdoch murdoch.duncan at gmail.com
Mon Dec 20 01:35:28 CET 2010


On 19/12/2010 7:21 PM, 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.

The name of var1 is var1, so I assume you mean the expression passed to 
your function and bound to var1.  In that case, what you want is

deparse(substitute(var1))

Watch out:  if the expression is really long, that can be a vector with 
more than one element.  See ?deparse for ways to deal with that.

Duncan Murdoch

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