[R] Can you turn an input into a variable name?

Greg Snow 538280 @end|ng |rom gm@||@com
Fri Oct 4 17:47:52 CEST 2019


This is in part answered by FAQ 7.21.

The most important part of that answer is at the bottom where it says
that it is usually better to use a list.

It may be safer to use a list for your case so that other important
variables do not become masked (hidden by the global variables you
just created).

Here is one way to do it:

txtcon <- textConnection("color=green
shape=circle")

textlines<-readLines(txtcon)
tmp <- strsplit(textlines, "=")

mylist <- list()
for(i in tmp) {
  mylist[[ i[1] ]] <- i[2]
}

or another option:

mylist[ sapply(tmp, `[`, 1)] <- sapply(tmp, `[`, 2)

If you know that you will not need a regular expression then you can
just use the `sep` argument to `read.table`:

txtcon <- textConnection("color=green
shape=circle")

tmp2 <- read.table(txtcon, sep='=', stringsAsFactors = FALSE)
mylist <- list()
mylist[ tmp2[,1] ] <- tmp2[,2]

Now you can use functions like `with`, `within`, `evalq`, etc. to work
with the elements of the list as if they were variables:

> with(mylist, ls() )
[1] "color" "shape"
> with(mylist, color)
[1] "green"
> mylist$shape
[1] "circle"
> vname <- 'color'
> mylist[[vname]]
[1] "green"
> evalq(paste('it is a', color, shape), mylist)
[1] "it is a green circle"

If you need regular expressions to find your names and values (extra
spaces, lines without '=', pairs embedded in longer sentences, etc.)
then look at the `regmatches` function or possibly the gsubfn package
(or other tools).


On Fri, Oct 4, 2019 at 12:59 AM April Ettington
<aprilettington using gmail.com> wrote:
>
> Let's say I am parsing a file with a list of parameters followed by an
> equal sign, and their corresponding values, eg:
>
> color=green
> shape=circle
>
> and I want to use this information to create a variable called color with
> the value 'green' and a variable shape with the value 'circle'.  However, I
> also want my code to be able to do this *when it doesn't know up front what
> the parameter names will be.  *So, if the file also included "age=7", it
> should still make a variable called age with the value '7', even though
> 'age' doesn't specifically appear anywhere in my code.  Is there a way to
> do this?
>
> Thank you,
> April
>
>         [[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.



-- 
Gregory (Greg) L. Snow Ph.D.
538280 using gmail.com



More information about the R-help mailing list