将变量重新分配给列表的元素 [英] Reassign variables to elements of list

查看:82
本文介绍了将变量重新分配给列表的元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在R中有一个对象列表,可以使用lapply在这些对象上执行不同的操作.但是,在下一步中,我只想将功能应用于列表的某些元素.因此,我想再次将列表拆分为原始变量. R中有为此的命令吗?甚至有可能,还是每次我都想创建新变量时都要这样做? 请参阅以下示例以弄清楚我的意思:

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.

有更好的方法吗?

推荐答案

假设您不熟悉R,更直观的方法可能是使用for循环.我确实认为Richard Scriven的方法更好.至少更简洁.

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)
}

话虽这么说,您的最终目标还是有点可疑.我建议您将结果保存在列表或矩阵中,特别是如果您不熟悉R.通过将所有结果包括在列表或矩阵中,您可以继续使用lapply和sapply之类的函数来处理结果.

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.

松散地说,Richard Scriven在评论中的方法是将列表中的每个元素转换为一个对象,然后将这些对象传递到封闭环境(在本例中为全局环境).他本可以将这些物体传递到任何环境中.例如,尝试

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)

请注意,test1test2test3现在位于环境e中.尝试e$test1ls(e).要深入了解括号,对ls的调用使用简单的正则表达式告诉mget要查找的对象的名称.有关更多信息,请查看 http://adv-r.had.co.nz/Environments.html .

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.

这篇关于将变量重新分配给列表的元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆