【问题标题】:get name of an object inside a loop获取循环内对象的名称
【发布时间】:2017-07-02 11:25:21
【问题描述】:

我知道从作为参数传递给函数的对象中获取名称的 deparse+substitute 技巧,但循环内的相同技巧不起作用。

我的代码(仅用于测试):

mylist <- list(first = c("lawyer","janitor"), second = c("engineer","housewife"))

for (element in names(mylist)){
  print(deparse(substitute(mylist[[element]])))
}

[1] "mylist[[element]]"
[1] "mylist[[element]]"

有没有办法得到结果?:

first
second

【问题讨论】:

  • 在你的例子中你可以使用print(element)..
  • names(mylist) 有什么问题?

标签: r


【解决方案1】:

使用lapply

lapply(mylist, function(x) { print(names(x))} )
# NULL
# NULL
# $first
# NULL
# 
# $second
# NULL

根据您的问题使用for 循环

for (element in names(mylist)){
  print(element)
}
# [1] "first"
# [1] "second"

【讨论】:

  • lapply 的做法略有不同,因为它将 names 函数应用于每个列表元素,返回 NULL 因为它们在示例中没有名称。
【解决方案2】:

使用“名称”

for (element in names(mylist)){
  print(as.name(element))
}

【讨论】:

    猜你喜欢
    • 2017-04-07
    • 1970-01-01
    • 2015-06-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-02-10
    • 1970-01-01
    相关资源
    最近更新 更多