How can I remove an element from a list?

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

    If you have a named list and want to remove a specific element you can try:

    lst <- list(a = 1:4, b = 4:8, c = 8:10)
    
    if("b" %in% names(lst)) lst <- lst[ - which(names(lst) == "b")]
    

    This will make a list lst with elements a, b, c. The second line removes element b after it checks that it exists (to avoid the problem @hjv mentioned).

    or better:

    lst$b <- NULL
    

    This way it is not a problem to try to delete a non-existent element (e.g. lst$g <- NULL)

提交回复
热议问题