string 使用 get() 访问 r 中的列表元素

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/9449542/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-09 01:23:47  来源:igfitidea点击:

Access list element in r using get()

stringrlistloops

提问by mike

I'm trying to use get() to access a list element in r, but am getting an error.

我正在尝试使用 get() 访问 r 中的列表元素,但出现错误。

example.list <- list()
example.list$attribute <- c("test")
get("example.list") # Works just fine
get("example.list$attribute") # breaks

Error in get("example.list$attribute") : object 'example.list$attribute' not found

get("example.list$attribute") 中的错误:找不到对象“example.list$attribute”

Any tips? I am looping over a vector of strings which identify the list names, and this would be really useful.

有小费吗?我正在遍历标识列表名称的字符串向量,这将非常有用。

回答by Josh O'Brien

Here's the incantation that you are probably looking for:

这是您可能正在寻找的咒语:

get("attribute", example.list)
# [1] "test"

Or perhaps, for your situation, this:

或者,对于您的情况,可能是这样:

get("attribute", eval(as.symbol("example.list")))
# [1] "test"

# Applied to your situation, as I understand it...

example.list2 <- example.list 
listNames <- c("example.list", "example.list2")
sapply(listNames, function(X) get("attribute", eval(as.symbol(X))))
# example.list example.list2 
#       "test"        "test" 

回答by Tommy

Why not simply:

为什么不简单:

example.list <- list(attribute="test")
listName <- "example.list"
get(listName)$attribute

# or, if both the list name and the element name are given as arguments:
elementName <- "attribute"
get(listName)[[elementName]]

回答by flodel

If your strings contain more than just object names, e.g. operators like here, you can evaluate them as expressions as follows:

如果您的字符串不仅仅包含对象名称,例如像这里这样的运算符,您可以将它们计算为表达式,如下所示:

> string <- "example.list$attribute"
> eval(parse(text = string))
[1] "test"

If your strings are all of the type "object$attribute", you could also parse them into object/attribute, so you can still getthe object, then extract the attribute with [[:

如果您的字符串都是“object$attribute”类型,您还可以将它们解析为对象/属性,这样您仍然可以get使用对象,然后使用以下命令提取属性[[

> parsed <- unlist(strsplit(string, "\$"))
> get(parsed[1])[[parsed[2]]]
[1] "test"

回答by Nick Stauner

flodel's answer worked for my application, so I'm gonna post what I built on it, even though this is pretty uninspired. You can access each list element with a forloop, like so:

flodel 的回答对我的应用程序有效,所以我会发布我在它上面构建的内容,即使这很没有灵感。您可以使用for循环访问每个列表元素,如下所示:

#==============  List with five elements of non-uniform length  ================#
example.list=
list(letters[1:5], letters[6:10], letters[11:15], letters[16:20], letters[21:26])
#===============================================================================#
#======  for loop that names and concatenates each consecutive element  ========#
derp=c();            for(i in 1:length(example.list))
{derp=append(derp,eval(parse(text=example.list[i])))}
derp #Not a particularly useful application here, but it proves the point.

I'm using code like this for a function that calls certain sets of columns from a data frame by the column names. The user enters a list with elements that each represent different sets of column names (each set is a group of items belonging to one measure), and the big data frame containing all those columns. The forloop applies each consecutive list element as the set of column names for an internal function*applied only to the currently named set of columns of the big data frame. It then populates one column per loop of a matrix with the output for the subset of the big data frame that corresponds to the names in the element of the list corresponding to that loop's number. After the forloop, the function ends by outputting that matrix it produced.

我正在将这样的代码用于一个函数,该函数通过列名从数据框中调用某些列集。用户输入一个包含元素的列表,每个元素代表不同的列名称集(每个集是属于一个度量的一组项目),以及包含所有这些列的大数据框。该for循环适用每个连续的列表元素作为内部功能集列名的*只适用于当前命名集的大数据帧的列。然后,它使用大数据框子集的输出填充矩阵的每个循环一列,该子集对应于与该循环编号对应的列表元素中的名称。在for循环之后,该函数通过输出它产生的矩阵来结束。

Not sure if you're looking to do something similar with your list elements, but I'm happy I picked up this trick. Thanks to everyone for the ideas!

不确定您是否希望对列表元素做类似的事情,但我很高兴我学会了这个技巧。感谢大家的想法!

"Second example" / tangential info regarding application in graded response model factor scoring:

“第二个例子”/关于分级响应模型因子评分应用的切向信息

Here's the function I described above, just in case anyone wants to calculate graded response model factor scores*in large batches...Each column of the output matrix corresponds to an element of the list (i.e., a latent trait with ordinal indicator items specified by column name in the list element), and the rows correspond to the rows of the data frame used as input. Each row should presumably contain mutually dependent observations, as from a given individual, to whom the factor scores in the same row of the ouput matrix belong. Also, I feel I should add that if all the items in a given list element use the exact same Likert scale rating options, the graded response model may be less appropriate for factor scoring than a rating scale model (cf. http://www.rasch.org/rmt/rmt143k.htm).

这是我上面描述的函数,以防万一有人想大批量计算分级响应模型因子分数*...输出矩阵的每一列对应于列表的一个元素(即,具有指定有序指标项的潜在特征按列表元素中的列名),行对应于用作输入的数据框的行。每一行应该大概包含相互依赖的观察,如来自给定个体的观察,输出矩阵的同一行中的因子得分属于该个体。此外,我觉得我应该补充一点,如果给定列表元素中的所有项目都使用完全相同的李克特量表评级选项,则分级响应模型可能比评级量表模型更不适合因子评分(参见http://www .rasch.org/rmt/rmt143k.htm)。

'grmscores'=function(ColumnNameList,DataFrame)   {require(ltm) #(Rizopoulos,2006)
x = matrix ( NA , nrow = nrow ( DataFrame ), ncol = length ( ColumnNameList ))
for(i in 1:length(ColumnNameList)) #flodel's magic featured below!#
{x[,i]=factor.scores(grm(DataFrame[,    eval(parse(text=   ColumnNameList[i]))]),
resp.patterns=DataFrame[,eval(parse(text= ColumnNameList[i]))])$score.dat$z1}; x}

Reference

参考

*Rizopoulos, D. (2006). ltm: An R package for latent variable modelling and item response theory analyses, Journal of Statistical Software, 17(5), 1-25. URL: http://www.jstatsoft.org/v17/i05/

*Rizopoulos, D. (2006)。ltm:用于潜在变量建模和项目响应理论分析的 R 包,统计软件杂志,17(5), 1-25。网址:http: //www.jstatsoft.org/v17/i05/