Re: [R] Create Variable names dynamically

From: David Winsemius <dwinsemius_at_comcast.net>
Date: Thu, 31 Mar 2011 16:11:29 -0500

On Mar 31, 2011, at 3:46 PM, Henrique Dallazuanna wrote:

> Take a look in ?assign
>
> On Thu, Mar 31, 2011 at 5:42 PM, Noah Silverman <noah_at_smartmediacorp.com
> > wrote:
>> Hi,
>>
>> I want to create variable names from within my code, but can't find
>> any documentation for this.
>>
>> An example is probably the best way to illustrate. I am reading
>> data in from a file, doing a bunch of stuff, and want to generate
>> variables with my output. (I could make a "list of lists" and name
>> all the elements, but I really want separate variables.)
>>
>>
>> #################
>> #This is just a dummy example, please excuse any shortcuts...
>>
>> data <- read.table("file", ....)
>> animals <- (data[,animal])
>> animals
>>> "cat", "dog", "horse" # Not known what these are before I read
>>> the data file
>>
>> # do a bunch of stuff
>>
>> mean_cat <- abc
>> var_cat <- dfd
>> mean_dog <- 123
>> var_dog <- 453
>> etc..
>> ##############

This form can be worked into your loop:

 > dat.a <- read.table(textConnection('cat dog horse\n1 2 3\n4 5 6\n7 8 9'), header=TRUE)
 > animals <- names(dat.a)
 > assign( paste("mean", animals[1], sep="_"), mean(dat.a[[animals[1]]]) )
 > mean_cat
[1] 4

Doesn't seem very R-ish, though.

>>
>> I thought of trying to use the paste() function to create the
>> variable name, but that doesn't work:
>> for( animal in animals){
>> paste("mean", animal "_") <- 123
>> }
>>
>> Any ideas???
>
> --
> Henrique Dallazuanna
> Curitiba-Paraná-Brasil
> 25° 25' 40" S 49° 16' 22" O
>
> ______________________________________________
> R-help_at_r-project.org mailing list
> 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.

David Winsemius, MD
Heritage Laboratories
West Hartford, CT



R-help_at_r-project.org mailing list
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. Received on Sun 03 Apr 2011 - 03:33:55 GMT

Archive maintained by Robert King, hosted by the discipline of statistics at the University of Newcastle, Australia.
Archive generated by hypermail 2.2.0, at Sun 03 Apr 2011 - 06:40:27 GMT.

Mailing list information is available at https://stat.ethz.ch/mailman/listinfo/r-help. Please read the posting guide before posting to the list.

list of date sections of archive