[R] evaluating the contents of a string

Thomas Lumley tlumley at u.washington.edu
Mon Oct 1 18:31:53 CEST 2001


On Fri, 28 Sep 2001, David A Richmond wrote:
<snip>
> is there a function to pass bname to such that dim returns the dimensions
> of b?
>
> like
> 	dim(somefunc(bname))
> returns
> 	[1] 3 3
>
> does 'somefunc' exist?

As already pointed out, eval(parse(text=bname)) will return the object
whose name is in the text string. Another way is get(bname), which is more
specific (it gets objects by name, rather than evaluating arbitrary code).

In general, this sort of question is frequently a sign that someone is
doing things the hard way.  There are some real situations where you need
to operate on strings like this, but they are fairly rare.

For example, if you have a collection of arrays and may want the
dimensions of any one of them, you could put them in a list


 listofarrays<-list()
 listofarrays$b <- matrix(1:9,3,3)
 dim(listofarrays$b)

and even
 bname<-"b"
 dim(listofarrays[[bname]])


	-thomas

Thomas Lumley			Asst. Professor, Biostatistics
tlumley at u.washington.edu	University of Washington, Seattle

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