[R] Convert a character string to variable names

Richard O'Keefe r@oknz @end|ng |rom gm@||@com
Wed Feb 9 02:17:17 CET 2022


"mtcars$disp" is not a variable name.
"mtcars" is a variable name, and
get("mtcars") will get the value of that variable
assign("mtcars", ~~whatever~~) will set it.
mtcars$disp is an *expression*,
where $ is an indexing operator
https://cran.r-project.org/doc/manuals/r-release/R-lang.html#Indexing
so what you want is
> mtcars <- list(cyl=4, disp=1.8)
> eval(parse(text="mtcars$disp"))
[1] 1.8

Though it's easy to do this, it's very seldom a good idea.
The combination of parse and eval can do ANYTHING, no matter
how disastrous.  Less powerful techniques are safer.
Where do these strings come from in the first place?
Why isn't it c("disp", "hp", "cyl")?

On Tue, 8 Feb 2022 at 11:56, Erin Hodgess <erinm.hodgess using gmail.com> wrote:

> Hello!
>
> I have a character string that is a vector of variable names.  I would like
> to use those names to access the variables and create a matrix.
> I tried the following:
>
> > .x
>
> [1] "mtcars$disp" "mtcars$hp"   "mtcars$cyl"
>
> > .y <- NULL
>
> > for(i in 1:3) {
>
> + .y[i] <- c(as.name(.x[[i]]))
>
> + }
>
> > .y
>
> [[1]]
>
> `mtcars$disp`
>
>
> [[2]]
>
> `mtcars$hp`
>
>
> [[3]]
>
> `mtcars$cyl`
>
>
> But I am having trouble converting the variables in .y into a matrix.
>
>
> I tried all kinds of stuff with bquote, deparse, do.call, but no good.
>
>
> I have a feeling that it's something simple, and I'm just not seeing it.
>
>
> Thanks,
>
> Erin
>
>
>
>
> Erin Hodgess, PhD
> mailto: erinm.hodgess using gmail.com
>
>         [[alternative HTML version deleted]]
>
> ______________________________________________
> R-help using r-project.org mailing list -- To UNSUBSCRIBE and more, see
> 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.
>

	[[alternative HTML version deleted]]



More information about the R-help mailing list