Skip to content

name of a name

4 messages · William Simpson, Baptiste Auguie, David Winsemius

#
I have quite a complicated problem that's hard to describe.

Suppose I have a dataframe d. I want to access the vector d$var, where
var is one of the variables in d. Just take for granted that there's a
good reason I want to do this as follows.

var<-"DeOxyA"
xx<-paste("d$",var, sep="")
mean(xx)
[1] NA
Warning message:
In mean.default(xx) : argument is not numeric or logical: returning NA
[1] 21.98904

How can I convert xx so I can do mean(xx), for example? Currently xx
is a character, not a variable.
as.numeric doesn't do it. I want R to see
mean(DeOxyA), not
mean("DeOxyA")

I'm stumped.

Thanks very much for any help.

Bill
#
Hi,

Try this,


d <- data.frame(a=1:4, b=3:6)

var <- "a"

mean(d[var])

## or, if you are not aware of
## fortune("parse")

xx <- paste("d$",var, sep="")
mean(eval(parse(text=xx)))

HTH,

baptiste




2009/11/19 William Simpson <william.a.simpson at gmail.com>:
#
Thanks very much Phil and Baptiste!
d[[var]]
is exactly what I wanted.
Sorry for being so inarticulate. I still couldn't describe my problem
if I wanted to! Anyway, now I have the solution.

Cheers
Bill

On Thu, Nov 19, 2009 at 9:39 AM, baptiste auguie
<baptiste.auguie at googlemail.com> wrote:
#
On Nov 19, 2009, at 4:39 AM, baptiste auguie wrote:

            
I tried get() on Simpson's pasted argument without success. Assuming  
the OP still wanted to use only text arguments, then this approach works

dfn <- "d"

get(dfn)[var]

So get() works only on complete objects and not on expressions that  
include extraction operations.
David Winsemius, MD
Heritage Laboratories
West Hartford, CT