Barnaba
Barnaba

Reputation: 1

Addressing to subsequent objects in loop function in R

I need to create a loop function in which I need to address to subsequent objects which names end with numbers i.e. object1, object 2, object3. So the code should look like this:

object1 <- c(1,2,3,4,5)
object2 <- c(2,3,4,5,6)
object3 <- c(3,4,5,6,7)

for (i in 1:3) {
    assign (paste0("new_object",i), mean(object???))
}

So I need a equivalent to just typing

new_object1 <- mean(object1)
new_object2 <- mean(object2)
new_object3 <- mean(object3)

Many thanks in advance!

Upvotes: 0

Views: 80

Answers (1)

akrun
akrun

Reputation: 887981

It would be get to return the values of that object by pasteing the 'i' with the 'object' string

for (i in 1:3) {
  assign(paste0("new_object",i), mean(get(paste0('object', i)))
 }

But, it is not a recommended way as it is creating new objects in the global env.


Instead, if the intention is to get the mean of all the 'object's,

sapply(mget(paste0("object", 1:3)), mean)

Or if there are more than three, use ls with pattern

sapply(mget(ls(pattern = '^object\\d+$')), mean)

Here, mget returns the value of more than one objects in a list, loop through the list with sapply and apply the mean function on the list element.


Creating objects can also be done from the list with list2env

out <- lapply( mget(ls(pattern = '^object\\d+$')), mean)
names(out) <- paste0('new_', names(out))
list2env(out, .GlobalEnv) # not recommended based on the same reason above

Upvotes: 2

Related Questions