本文介绍了使用存储为字符串的名称以编程方式选择列表元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个清单

myList = list(a = 1, b = 2)
names(myList)
# [1] "a" "b" 

我想通过存储在字符串中的名称从"myList"中选择元素.

I want to select element from 'myList' by name stored in as string.

for (name in names(myList)){
     print (myList$name)
}

这不起作用,因为名称="a","b".我的选择行实际上是说myList$"a"myList$"b".我也尝试过:

This is not working because name = "a", "b". My selecting line actually saying myList$"a" and myList$"b". I also tried:

print(myList$get(name))
print(get(paste(myList$, name, sep = "")))

但是没有用.如果您能告诉我该怎么做,我非常感谢.

but didn't work. Thank you very much if you could tell me how to do it.

推荐答案

$进行完全匹配和部分匹配,myList$name等效于

$ does exact and partial match, myList$name is equivalent to

`$`(myList, name)

正如@Frank所指出的那样,第二个参数name将不被求值,但将被视为文字字符串.尝试?`$`并查看文档.

As @Frank pointed out, the second argument name won't be evaluated, but be treated as a literal character string. Try ?`$`and see the document.

在您的示例中. myList$name将尝试在myList

In your example. myList$name will try to look for name element in myList

这就是为什么您需要myList[[name]]

这篇关于使用存储为字符串的名称以编程方式选择列表元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-24 20:00