2012-01-28 64 views
22

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

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会是红色的两条曲线

+0

但是,但是,但是...你从来没有给一个名字到data.frame。我们应该如何打印一些不存在的东西? – 2012-01-28 22:50:45

+0

@DWin true,但是当我将向量包装到一个表和数据框中时,它将保留L2中的原始向量名称。 'L2'和'name(L2)'之后的'browser()'显示这个'Browse [1]>名称(L2) [1]“x”“y” – 2012-01-28 23:18:09

+0

所以你想要列名或名称的对象? – 2012-01-28 23:24:50

回答

8

制作一个小调整到内部功能和使用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) 
+0

谢谢你,完美的作品。我认为可能会有一种解决方案,但我的面条不可能这样想。 – 2012-01-28 23:11:36

53

是的,它存在的顶部:)只要使用

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

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

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

为了清楚起见,我添加了更多上下文,但名称(LIST)[1]不起作用。 – 2012-01-28 20:49:42

+1

明显的解决方案,它用循环替换'lapply',你完成了......我怀疑有没有什么干净的出路,就像'lapply'一样,你的函数不知道正在处理哪个索引。 – 2012-01-28 21:03:11

+0

我害怕循环是答案。我真的很糟糕的循环。 R是我唯一的语言,所以我失去了一个适用的解决方案,或者迷失方向。 – 2012-01-28 22:00:08