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

Jim Lemon drj|m|emon @end|ng |rom gm@||@com
Fri Oct 4 12:58:35 CEST 2019


Hi April,
Try this:

# this could be done from a file
textlines<-read.table(text="color=green
 shape=circle
 age=17
 name=Jim",
 stringsAsFactors=FALSE)
for(i in 1:length(textlines)) {
 nextline<-unlist(strsplit(textlines[i,1],"="))
 assign(nextline[1],nextline[2])
}
color
[1] "green"
shape
[1] "circle"
age
[1] "17"
name
[1] "Jim"

Jim

On Fri, Oct 4, 2019 at 4:59 PM 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.



More information about the R-help mailing list