How can I remove an element from a list?

前端 未结 16 1439
傲寒
傲寒 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:50

    Use - (Negative sign) along with position of element, example if 3rd element is to be removed use it as your_list[-3]

    Input

    my_list <- list(a = 3, b = 3, c = 4, d = "Hello", e = NA)
    my_list
    # $`a`
    # [1] 3
    
    # $b
    # [1] 3
    
    # $c
    # [1] 4
    
    # $d
    # [1] "Hello"
    
    # $e
    # [1] NA
    

    Remove single element from list

     my_list[-3]
     # $`a`
     # [1] 3
    
     # $b
     # [1] 3
    
     # $d
     # [1] "Hello"
    
     # $e
     [1] NA
    

    Remove multiple elements from list

     my_list[c(-1,-3,-2)]
     # $`d`
     # [1] "Hello"
    
     # $e
     # [1] NA
    

     my_list[c(-3:-5)]
     # $`a`
     # [1] 3
    
     # $b
     # [1] 3
    

     my_list[-seq(1:2)]
     # $`c`
     # [1] 4
    
     # $d
     # [1] "Hello"
    
     # $e
     # [1] NA
    

提交回复
热议问题