Skip to content

Loop on vector name

5 messages · Megh Dal, Henrique Dallazuanna, Dimitris Rizopoulos +1 more

#
[My previous message rejected, therefore I am sending same one with some modification]

I have 3 vectors with object name : dat1, dat2, dat3

Now I want to create a loop, like :

for (i in 1:3)
   {
    cat(sd(dati))
   }

How I can do this in R?

Regards,
#
you need to get(), e.g., try this:

dat1 <- rnorm(5)
dat2 <- rnorm(6)
dat3 <- rnorm(7)

lis <- lapply(paste("dat", 1:3, sep = ""), get)
lis
sapply(lis, sd)


I hope it helps.

Best,
Dimitris
Megh Dal wrote:

  
    
#
Others have answered the question that you asked (it is also a variation of Faq 7.21), but here is an answer to the question that you should have asked:

When working with datasets like this, it is better to create a list rather than separate objects with names like dat1, dat2, etc.

For example:
Now your loop can be:
Or even simpler:
And when you are through with the data, you only need to delete one object, or copy one object, or save one object, etc.

Hope this helps,
1 day later
#
Thanks for this mail. It runs perfectly, but now I stuck on how to convert the result in a vector format for further matrix-compputation. e.g. How to convert "sapply(lis, sd)" to vector?
--- On Wed, 9/17/08, Dimitris Rizopoulos <d.rizopoulos at erasmusmc.nl> wrote: