user3032689
user3032689

Reputation: 667

Reassign variables to elements of list

I have a list of objects in R on which I perform different actions using lapply. However in the next step I would like to apply functions only to certain elements of the list. Therefore I would like to split the list into the original variables again. Is there a command in R for this? Is it even possible, or do I have to create new variables each time I want to do this? See the following example to make clear what I mean:

# 3 vectors:
test1 <- 1:3
test2 <- 2:6
test3 <- 8:9

# list l:
l <- list(test1,test2,test3)

# add 3 to each element of the list:
l <- lapply(l, function(x) x+3)

# In effect, list l contains modified versions of the three test vectors

Question: How can I assign those modifications to the original variables again? I do not want to do:

test1 <- l[[1]]
test2 <- l[[2]]
test3 <- l[[3]]
# etc.

Is there a better way to do that?

Upvotes: 0

Views: 281

Answers (1)

Jacob H
Jacob H

Reputation: 4513

A more intuitive approach, assuming you're new to R, might be to use a for loop. I do think that Richard Scriven's approach is better. It is at least more concise.

for(i in seq(1, length(l))){
    name <- paste0("test",i)
    assign(name, l[[i]] + 3)
}

That all being said, your ultimate goal is a bit dubious. I would recommend that you save the results in a list or matrix, especially if you are new to R. By including all the results in a list or matrix you can continue to use functions like lapply and sapply to manipulate your results.

Loosely speaking Richard Scriven's approach in the comments is converting each element of your list into an object and then passing these objects to the enclosing environment which is the global environment in this case. He could have passed the objects to any environment. For example try,

e <- new.env()
list2env(lapply(mget(ls(pattern = "test[1-3]")), "+", 3), e)

Notice that test1, test2 and test3 are now in environment e. Try e$test1 or ls(e). Going deeper in to the parenthesis, the call to ls uses simple regular expressions to tell mget the names of the objects to look for. For more, take a look at http://adv-r.had.co.nz/Environments.html.

Upvotes: 1

Related Questions