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

问题描述

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

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:

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

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.

这篇关于为什么对R而言,对列表元素的assign()值不起作用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-24 10:57