基于变量名称R的名称列表元素 [英] Name list elements based on variable names R
问题描述
我想将元素动态添加到一个空列表中.列表中的每个元素应在一组变量会自动命名,这些变量的值会有所不同.
I want to add elements to an empty list on the fly. Each element in the list should be named automatically after a set of variables which value will vary.
但是,我似乎无法找到一种在没有错误的情况下即时命名列表元素的方法.考虑下面的示例:
However, I cannot seem to find a way to name list elements on the fly without getting errors. Consider the example below:
L <- list()
var1 <- "wood"
var2 <- 1.0
var3 <- "z4"
varname <- paste(var1, as.character(var2), var3, sep="_")
# This works fine:
L$"wood_1_z4" <- c(0,1)
L$"wood_1_z4"
0 1
# This doesn't!!
L$paste(var1, as.character(var2), var3, sep="_") <- c(0,1)
Error in L$paste(var1, as.character(var2), var3, sep = "_") <- c(0, 1) :
invalid function in complex assignment
# Ths doesn't either ...
L$eval(parse(text = "varname")) <- c(0,1)
Error in L$eval(parse(text = "varname")) <- c(0, 1) :
target of assignment expands to non-language object
有没有办法做到这一点?
Is there a way to do this?
推荐答案
您不能使用<-
运算符将其分配给paste()
(我相信eval()
函数也是如此).相反,您需要使用[[
运算符或使用names()
函数.您可以这样操作:
You cannot assign to paste()
using the <-
operator (and I believe this is true for the eval()
function as well). Instead, you need to either use the [[
operator or use the names()
function. You can do this like so:
L <- list()
var1 <- "wood"
var2 <- 1.0
var3 <- "z4"
varname <- paste(var1, as.character(var2), var3, sep="_")
# Using [[
L[[varname]] <- c(0,1)
> L
$wood_1_z4
[1] 0 1
# Using names()
L[[1]] <- c(0,1)
names(L)[1] <- varname
> L
$wood_1_z4
[1] 0 1
一种更有效的方法可能是使用一个既创建值又命名列表元素的函数,或者甚至是一个仅创建值的函数-如果您随后使用sapply
,则可以使用以下命令命名每个列表元素调用函数和USE.NAMES
选项的参数.
A more effective way to do this might be to use a function that both creates the value and names the list element, or even one that just creates the value - if you then use sapply
you can name each list element using arguments from the call to your function and the USE.NAMES
options.
通常来说,当列表的最终大小和结构不为人所知时,R对于随时间增长的列表并没有得到很好的优化.虽然可以做到,但更"R-ish"的做法是提前弄清楚结构.
In a general sense, R isn't really well-optimized for growing lists over time when the final size and structure of the list aren't well-known. While it can be done, a more "R-ish" way to do it would be to figure out the structure ahead of time.
这篇关于基于变量名称R的名称列表元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!