1

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

3
  • Or use list2env after placing the values in a list. Commented Feb 12, 2015 at 6:16
  • 2
    Don't name your variables like this. You'll be better off placing values in a list or vector. Commented Feb 12, 2015 at 6:29
  • @MrFlick: thanks a lot, thats a better way Commented Feb 13, 2015 at 9:52

1 Answer 1

2

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)
Sign up to request clarification or add additional context in comments.

1 Comment

Your 100% right, but the question asked for creating objects so I gave him an answer. stuff <- lapply(1:length(N),runif(10)) would be much quicker.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.