Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
356 views
in Technique[技术] by (71.8m points)

r - Extract names of objects from list

I have a list of objects. How do I grab the name of just one object from the list? As in:

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) is not correct because it returns "A" and "B".

Just for context I am plotting a series of data frames that are stored in a list. As I come to each data.frame I want to include the name of the data.frame as the title. So an answer of names(LIST)[1] is not correct either.

EDIT: I added code for more context to the problem

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)

If this works the names x and y will be in red at the top of both plots

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

You can just use:

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

Obviously the names of the first element is just

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...