Reassign variables to elements of list

断了今生、忘了曾经 提交于 2019-12-12 04:17:49

问题


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?


回答1:


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.



来源:https://stackoverflow.com/questions/34052585/reassign-variables-to-elements-of-list

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!