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
Solution 1:
You can just use:
> names(LIST)
[1] "A" "B"
Obviously the names of the first element is just
> names(LIST)[1]
[1] "A"
Solution 2:
Making a small tweak to the inside function and using lapply on an index instead of the actual list itself gets this doing what you want
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)