从列表中提取对象的名称

时间:2012-01-28 20:33:30

标签: r

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

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

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

仅针对上下文我正在绘制一系列存储在列表中的数据框。当我来到每个data.frame时,我想要包含data.frame的名称作为标题。所以名称(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将在两个图的顶部显示为红色

2 个答案:

答案 0 :(得分:73)

是的,它存在:)只需使用

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

显然,第一个元素的名称只是

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

答案 1 :(得分:10)

对内部函数进行小调整并在索引上使用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)