-2

I want to assign 10 variables the same value such as

v1 <-  1:10
v2 <-  1:10
....
v10 <-  1:10

eval(paste("v",1:10,"<-","1:10",sep=""))  #can not get the result

How can assign many variables the same value in a smart way in R ?

Netloh
  • 4,338
  • 4
  • 25
  • 38
showkey
  • 482
  • 42
  • 140
  • 295

3 Answers3

7

DONT is the smart way. Make a list.

> mylist=list()
> for(i in 1:10){mylist[[i]]=1:10}
> mylist[[4]]
 [1]  1  2  3  4  5  6  7  8  9 10

Why? well because once you've created v1 to v10 you are going to want to know how to get v for some value of i and now you have two problems.

FWIW (and IW very little) you use assign and get to do those things, but if you cant understand the help pages for those then you shouldn't be using them.

Spacedman
  • 92,590
  • 12
  • 140
  • 224
3

Completely agree with @Spacedman. But just for the sake of completeness, here's how you would do it, if you choose to ignore good advice:

lapply(paste0("v", 1:10), assign, value=1:10, pos=1)

Alternatively, using the method that you suggested, here's a second way:

lapply(paste("v",1:10,"<-","1:10",sep=""), function(x){
  eval(parse(text=x), envir=.GlobalEnv)
})
shadow
  • 21,823
  • 4
  • 63
  • 77
1

Note - I agree with Spacedman that this may not be desirable. However here is another way to do it

v1<-v2<-v3<-v4<-v5<-v6<-v7<-v8<-v9<-v10<-1:10

This is much less elegent than shadow's method, but if the variables all had different names (eg "v1", "countX", "fish" etc.) it would work and would be fairly readable in your code.

John Paul
  • 12,196
  • 6
  • 55
  • 75