Extract names of objects from list

前端 未结 2 844
孤街浪徒
孤街浪徒 2020-11-30 01:32

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$         


        
相关标签:
2条回答
  • 2020-11-30 02:11

    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)
    
    0 讨论(0)
  • 2020-11-30 02:21

    You can just use:

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

    Obviously the names of the first element is just

    > names(LIST)[1]
    [1] "A"
    
    0 讨论(0)
提交回复
热议问题