[R] creating a dynamic output vector

Rolf Turner r.turner at auckland.ac.nz
Thu Nov 8 04:27:19 CET 2007


On 8/11/2007, at 3:00 PM, Steve Powers wrote:

> Everyone is assuming I know what the output data are, or that they  
> come
> out from my model in some easily called vector. But I don't, and  
> they do
> not. The outputs are hidden, and all are separate variables that  
> need to
> be called. Also which ones come out after a given run will vary each
> time. All I have to reference the desired output variables are the  
> names
> of every POTENTIAL output in character format, all in one vector.

	This doesn't make a lot of sense.  What does ``The outputs are
	hidden'' mean?  What does ``all are separate variables'' mean?
	What does ``that need to be *called*'' (emphasis mine) mean?

	It sounds as if	you have software (a script?) that is creating global
	variables in your workspace rather than a function returning a list.
	This is bad practice and makes it hard to use the beautiful  
facilities of R.

	BTW you cannot mix types in a single *vector*; if you have scalars
	of different types (numeric and character) and you want to store
	them in a single object, you have to use a *list* rather than a
	vector.

	If you have a subset of varA, ..., varZ as global variables in your
	workspace, you can put them into a *list* of length 26, in the
	proper slots as follows:

		nms <- paste("var",LETTERS,sep="")
		res <- lapply(nms,function(x){if(exists(x)) get(x) else NA})

	I emphasize however that if this is indeed your approach it is bad
	and dangerous programming.

> In any event, if anyone knows how to simply put all workspace variable
> names into one character vector, and their values/strings in another
> vector, that should work and I could take it from there (all I need  
> are
> the one element variables, not vectors or data frames). Initially I
> messed around for awhile with ls() and ls.str() with no luck. Can't  
> get
> those data into a useful format.

	To put ***all*** the names of all variables in a workspace into
	a character vector, you use ls()!!! (Like, I mean, huh?)

	You ***cannot*** put ``their values'' into another ***vector***
	unless they are all scalars of the same type.  You can (easily)
	put their values into a list:

		all.nms <- ls()
		all.res <- lapply(all.nms,get)

			cheers,

				Rolf Turner

######################################################################
Attention:\ This e-mail message is privileged and confid...{{dropped:9}}



More information about the R-help mailing list