user2876812
user2876812

Reputation: 336

need to assign variables some values in a loop in R

I need to assign variables some values in a loop

Eg:

abc_1<-  
abc_2<-
abc_3<-
.....

something like:

for(i in 1:20)
{
 paste("abc",i,sep="_")<-some calculated value
}

I have tried to use paste as above but it doesn't work. How could this be done.Thanks

Upvotes: 1

Views: 144

Answers (1)

Steve Bronder
Steve Bronder

Reputation: 936

assign() and paste0() should help you.

for example:

object_names <- paste0("abc",1:20)

for (i in 1:20){
   assign(object_names[i],runif(40))
}

assign() takes the string in object_names and assigns the function in the second argument to each name. When you place a numeric vector inside of paste0() it gives back a character vector of concatenated values for each value in the numeric vector.

edit:

As Gregor says below, this is much better to do in a list because:

  1. It will be faster.
  2. When making a large number of things you probably want to do the same thing to each of them. lapply() is very good at this.

For example:

N <- 20
# create random numbers in list
abcs <- lapply(1:N,function(i) runif(40))
# multiply each vector in list by 10
abc.mult <- lapply(1:length(abcs), function(i) abcs[[i]] * 10)

Upvotes: 2

Related Questions