为什么不将assign() 值分配给R 中的列表元素? [英] Why doesn't assign() values to a list element work in R?

查看:20
本文介绍了为什么不将assign() 值分配给R 中的列表元素?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试在列表中的对象中使用赋值.我想做的是改变一些元素.例如:

I'm trying to use assign values in an object in a list. What I want to do is change some elements. For example:

x <- list()
x$test <- 1
assign("x$test", 2)
x$test == 1
     [1] TRUE

有什么想法吗?我需要使用assign,因为我正在构建一个函数,它将列表(x) 中的对象的名称作为输入.

Any thoughts? I need to use assign because I am building a function which will take the names of the objects within the list (x) as inputs.

推荐答案

看起来你运气不好.来自帮助文件:

Looks like you're out of luck. From the help file:

‘assign’ 不分派赋值方法,因此它不能用于设置向量、名称、属性等元素

‘assign’ does not dispatch assignment methods, so it cannot be used to set elements of vectors, names, attributes, etc.

请注意,分配给附加列表或数据框会改变附加副本而不是原始对象:参见附加"和与".

Note that assignment to an attached list or data frame changes the attached copy and not the original object: see ‘attach’ and ‘with’.

如果您将 names(x) 作为输入传递,您不能使用:

If you're passing names(x) as input, couldn't you use:

nms <- names(x)
for ( n in nms )
    x[[n]] <- 'new_value'

另外,你打算让你的函数修改一些全局变量吗?例如:

Also, are you intending for your function to modify some global variable? e.g.:

x <- list(test=1)

f <- function(...)
   x$test <- 2

f() # want x$test = 2 ??

因为这不起作用(范围问题).您可以通过一些步法(<<-)使其工作,但这通常被认为是不好的做法,因为很容易将无意的错误引入您的代码中.

Because this won't work (scope problems). You can make it work with a bit of footwork (<<-), but this is generally considered bad practice as it's easy to intrtoduce unintentional bugs into your code.

如果您能举例说明您为什么需要此功能/它的用途是什么,我们可以帮助您找到替代解决方案.

If you could give an example of why you want this function/what purpose it will serve, we could help you find an alternative solution.

这篇关于为什么不将assign() 值分配给R 中的列表元素?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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