【问题标题】:Extract names of objects from list从列表中提取对象的名称
【发布时间】:2012-02-21 07:58:40
【问题描述】:

我有一个对象列表。如何从列表中仅获取一个对象的名称?如:

LIST <- list(A=1:5, B=1:10)
LIST$A
some.way.cool.function(LIST$A)  #function I hope exists
"A"   #yay! it has returned what I want

names(LIST) 不正确,因为它返回“A”和“B”。

仅出于上下文考虑,我正在绘制一系列存储在列表中的数据框。当我来到每个 data.frame 时,我想包含 data.frame 的名称作为标题。因此,names(LIST)[1] 的答案也不正确。

编辑:我为问题添加了更多上下文的代码

x <- c("yes", "no", "maybe", "no", "no", "yes")
y <- c("red", "blue", "green", "green", "orange")
list.xy <- list(x=x, y=y)

WORD.C <- function(WORDS){
require(wordcloud)

L2 <- lapply(WORDS, function(x) as.data.frame(table(x), stringsAsFactors = FALSE))

    FUN <- function(X){
        windows() 
        wordcloud(X[, 1], X[, 2], min.freq=1)
        mtext(as.character(names(X)), 3, padj=-4.5, col="red")  #what I'm trying that isn't working
    }
    lapply(L2, FUN)
}

WORD.C(list.xy)

如果可行,名称 x 和 y 将在两个图的顶部显示为红色

【问题讨论】:

  • 但是,但是,但是……你从来没有给 data.frame 起个名字。我们应该如何打印不存在的东西?
  • @DWin true 但是当我将向量包装到表格和数据框中时,它会在 L2 中保留原始向量名称。在 L2 和 names(L2) 之后的 browser() 揭示了这个 Browse[1]&gt; names(L2) [1] "x" "y"
  • 那么你想要列名还是对象名?
  • @DWin 对象的名称(称为 x 和 y 的数据帧)。对不起,如果我不清楚这一点。这个解释起来有点松懈。 Dason 显示的是正确的。
  • 这里的问题和答案都充满了不必要的细节:(

标签: r


【解决方案1】:

你可以使用:

> names(LIST)
[1] "A" "B"

显然第一个元素的名字只是

> names(LIST)[1]
[1] "A"

【讨论】:

  • 为了清楚起见,我添加了更多上下文,但名称(LIST)[1] 不起作用。
  • 用循环替换lapply 的明显解决方案,你就完成了......我怀疑有任何干净的出路,就像lapply 你的函数不知道正在处理哪个索引.
  • 我担心循环是答案。我对循环真的很不好。 R 是我唯一的语言,所以如果没有应用解决方案,我会迷失方向或迷失方向。
【解决方案2】:

对内部函数进行小幅调整,并在索引上使用 lapply 而不是实际的列表本身,这样就可以完成您想要的操作

x <- c("yes", "no", "maybe", "no", "no", "yes")
y <- c("red", "blue", "green", "green", "orange")
list.xy <- list(x=x, y=y)

WORD.C <- function(WORDS){
  require(wordcloud)

  L2 <- lapply(WORDS, function(x) as.data.frame(table(x), stringsAsFactors = FALSE))

  # Takes a dataframe and the text you want to display
  FUN <- function(X, text){
    windows() 
    wordcloud(X[, 1], X[, 2], min.freq=1)
    mtext(text, 3, padj=-4.5, col="red")  #what I'm trying that isn't working
  }

  # Now creates the sequence 1,...,length(L2)
  # Loops over that and then create an anonymous function
  # to send in the information you want to use.
  lapply(seq_along(L2), function(i){FUN(L2[[i]], names(L2)[i])})

  # Since you asked about loops
  # you could use i in seq_along(L2) 
  # instead of 1:length(L2) if you wanted to
  #for(i in 1:length(L2)){
  #  FUN(L2[[i]], names(L2)[i])
  #}
}

WORD.C(list.xy)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-12-13
    • 2020-12-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-07-30
    相关资源
    最近更新 更多