[R] multiple assignments ?

Bert Gunter gunter.berton at gene.com
Tue Aug 24 17:39:05 CEST 2010


None of this would work if the list is long. Isn't this an obvious
task for a loop, explicit or implicit?

e.g.

for(i in 1:100)assign(paste("vec",i,sep=""), vector("integer",5))

or probably better because it creates a list structure:

## warning, untested. You may have to fool with the syntax a bit:

listofempties <- lapply(1:100, vector,mode="integer",length=5)

## you can name the components with names(listofempties) <-
paste("vec",1:100,sep="")

HOWEVER, I rather doubt that any of this is necessary: that is, it is
rarely necessary or wise in R to first create empty objects and then
populate them. Using lists and list operations usually allows both to
be done more efficiently and conveniently in one step.

--
Bert Gunter
Genentech Nonclinical Statistics

On Tue, Aug 24, 2010 at 8:19 AM, r.ookie <r.ookie at live.com> wrote:
> Do you mean something like this?
>
>>
>  n <- 5
>
>>
>  (vec1 <- matrix(rep(1, n)))
>     [,1]
> [1,]    1
> [2,]    1
> [3,]    1
> [4,]    1
> [5,]    1
>
>>
>  (vec2 <- matrix(rep(2, n)))
>     [,1]
> [1,]    2
> [2,]    2
> [3,]    2
> [4,]    2
> [5,]    2
>
>>
>  (vec3 <- matrix(rep(3, n)))
>     [,1]
> [1,]    3
> [2,]    3
> [3,]    3
> [4,]    3
> [5,]    3
>
>>
>
>
>>
>  (vec <- matrix(c(vec1, vec2, vec3)))
>      [,1]
>  [1,]    1
>  [2,]    1
>  [3,]    1
>  [4,]    1
>  [5,]    1
>  [6,]    2
>  [7,]    2
>  [8,]    2
>  [9,]    2
> [10,]    2
> [11,]    3
> [12,]    3
> [13,]    3
> [14,]    3
> [15,]    3
>
>>
>
> On Aug 24, 2010, at 4:58 AM, Maas James Dr (MED) wrote:
>
> Simple one, have read and googled, still no luck!
>
> I want to create several empty vectors all of the same length.
>
> I would like multiple empty vectors (vec1, vec2, vec3) and want to create them all in one line.
>
> I've tried
>
> vec1,vec2,vec3 <- vector(length=5)
> and
> c(vec1,vec2,vec3) <- vector(length=5)
>
> and several other attempts but nothing seems to work ... suggestions?
>
> Thanks
>
> Jim
>
> ===============================
> Dr. Jim Maas
> University of East Anglia
>
>
>        [[alternative HTML version deleted]]
>
> ______________________________________________
> 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.
>
> ______________________________________________
> 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