How can I remove an element from a list?

前端 未结 16 1437
傲寒
傲寒 2020-11-28 01:21

I have a list and I want to remove a single element from it. How can I do this?

I\'ve tried looking up what I think the obvious names for this function would be in

16条回答
  •  迷失自我
    2020-11-28 01:39

    In the case of named lists I find those helper functions useful

    member <- function(list,names){
        ## return the elements of the list with the input names
        member..names <- names(list)
        index <- which(member..names %in% names)
        list[index]    
    }
    
    
    exclude <- function(list,names){
         ## return the elements of the list not belonging to names
         member..names <- names(list)
         index <- which(!(member..names %in% names))
        list[index]    
    }  
    aa <- structure(list(a = 1:10, b = 4:5, fruits = c("apple", "orange"
    )), .Names = c("a", "b", "fruits"))
    
    > aa
    ## $a
    ##  [1]  1  2  3  4  5  6  7  8  9 10
    
    ## $b
    ## [1] 4 5
    
    ## $fruits
    ## [1] "apple"  "orange"
    
    
    > member(aa,"fruits")
    ## $fruits
    ## [1] "apple"  "orange"
    
    
    > exclude(aa,"fruits")
    ## $a
    ##  [1]  1  2  3  4  5  6  7  8  9 10
    
    ## $b
    ## [1] 4 5
    

提交回复
热议问题