从列表中提取对象的名称

Tyl*_*ker 36 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
Run Code Online (Sandbox Code Playgroud)

名称(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)
Run Code Online (Sandbox Code Playgroud)

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

Dr *_*r G 79

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

> names(LIST)
[1] "A" "B"
Run Code Online (Sandbox Code Playgroud)

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

> names(LIST)[1]
[1] "A"
Run Code Online (Sandbox Code Playgroud)

  • 为了清楚起见,我添加了更多上下文,但是名称(LIST)[1]不起作用。 (2认同)

Das*_*son 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)
Run Code Online (Sandbox Code Playgroud)