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 ?
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.
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)
})
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.