[R] Referring to an object by a variable containing its name: 6 failures

andrewH ahoerner at rprogress.org
Sat Sep 17 09:04:49 CEST 2011


Dear Folks -- 
The anonymous poster ("rmailbox") is perfectly correct.  I had forgotten you
could use names in this way.  When referring to rows or columns by name
rather than by number, I usually use either attach() or the $ operator,
neither of which works here. If anyone understands why data.df[,colName]
works in this setting but datadf$colName and the use of as.symbol(colName)
after attach(data.df) do not work, i would love an explanation, because I
sure don't.

Thanks, Timothy, for helping to clarify what I was trying to do. You are
exactly right, and your analogy to the $$ command in PHP – a command that
works -- was thereby more perfect than my analogy to things in R which do
not work. 

Elk's suggestion to use the get() function was very welcome, as I had never
really understood what get() was for, and this is a great use that often
arises. However, for this purpose, get() is somewhat capricious in its
effectiveness. “get(colName)” works as the operand of class(), length(),
mode(), and summary(), but it does not work for typeof(), where it returns
this error:  
"Error in eval(substitute(expr), data, enclos = parent.frame()) :  numeric
'envir' arg not of length one"
And it does not work for str(), where it treats the variable name as a
character string rather than a symbol.

Again, I do nut understand what distinguishes the functions for which Elk's
solution works from those for which it does not. Does anybody know? Ideas
welcome.

--and thanks again for all the help.

andrewH


--
View this message in context: http://r.789695.n4.nabble.com/Referring-to-an-object-by-a-variable-containing-its-name-6-failures-tp3817129p3819813.html
Sent from the R help mailing list archive at Nabble.com.



More information about the R-help mailing list