[R] How to create multi variables

Jeff Newmiller jdnewmil at dcn.davis.CA.us
Wed May 14 03:43:21 CEST 2014


What is wrong with

myvec <- vector( "numeric", 10 )
for ( i in 1:10 ) {
  myvec[ i ] <- i
}

?

If you are using assign, IMHO you are probably doing whatever you are doing wrong.

If you want named elements, give the vector names:

names( myvec ) <- paste0( "t", 1:10 )

and you can refer to them

myvec[ "t3" ]

Go read the "Introduction to R" document again... particularly the discussion of indexing.
---------------------------------------------------------------------------
Jeff Newmiller                        The     .....       .....  Go Live...
DCN:<jdnewmil at dcn.davis.ca.us>        Basics: ##.#.       ##.#.  Live Go...
                                      Live:   OO#.. Dead: OO#..  Playing
Research Engineer (Solar/Batteries            O.O#.       #.O#.  with
/Software/Embedded Controllers)               .OO#.       .OO#.  rocks...1k
--------------------------------------------------------------------------- 
Sent from my phone. Please excuse my brevity.

On May 13, 2014 5:47:12 PM PDT, Yuanzhi Li <Yuanzhi.Li at USherbrooke.ca> wrote:
>Hi, everyone
>
>I want to create a series of variables (e.g. t1, t2..., t10) which
>could 
>be used in loops. My idea is to use function "assign"
>
>for (i in 1:10)
>{
>   assign(paste("t",i,sep=""), FUN) # allocate the value from FUN to 
>variable ti
>}
>
>But when I create a vector containing the names of these variables and 
>want to use the variables according to the subscript, it doesn't works.
>
>t<-noquote(paste("t",1:10,sep=""))
>t[1]
>t1
>it returns only the name of variable t1, but not the value allocated to
>
>t1 by FUN. So what should I do to realize this?
>
>Or is there any better way to do this?
>
>Can we define a series of variables which can be used according to the 
>subscript like
>t<-f(t1, t2..., t10),
>then we have 10 variables which can be used directly?
>for(i in 1:10)
>{
>  t[i]<-FUN# with the fines variables we can directly assign the value 
>of FUN to ti
>}
>These are just my thoughts, I don't know whether there are available R 
>codes to realized it. I am looking forward any help from you.
>
>Thanks in advance!
>
>Yuanzhi
>
>______________________________________________
>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.



More information about the R-help mailing list