How can I remove an element from a list?

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

    There's the rlist package (http://cran.r-project.org/web/packages/rlist/index.html) to deal with various kinds of list operations.

    Example (http://cran.r-project.org/web/packages/rlist/vignettes/Filtering.html):

    library(rlist)
    devs <- 
      list(
        p1=list(name="Ken",age=24,
          interest=c("reading","music","movies"),
          lang=list(r=2,csharp=4,python=3)),
        p2=list(name="James",age=25,
          interest=c("sports","music"),
          lang=list(r=3,java=2,cpp=5)),
        p3=list(name="Penny",age=24,
          interest=c("movies","reading"),
          lang=list(r=1,cpp=4,python=2)))
    
    list.remove(devs, c("p1","p2"))
    

    Results in:

    # $p3
    # $p3$name
    # [1] "Penny"
    # 
    # $p3$age
    # [1] 24
    # 
    # $p3$interest
    # [1] "movies"  "reading"
    # 
    # $p3$lang
    # $p3$lang$r
    # [1] 1
    # 
    # $p3$lang$cpp
    # [1] 4
    # 
    # $p3$lang$python
    # [1] 2
    
    0 讨论(0)
  • 2020-11-28 01:52

    I don't know R at all, but a bit of creative googling led me here: http://tolstoy.newcastle.edu.au/R/help/05/04/1919.html

    The key quote from there:

    I do not find explicit documentation for R on how to remove elements from lists, but trial and error tells me

    myList[[5]] <- NULL

    will remove the 5th element and then "close up" the hole caused by deletion of that element. That suffles the index values, So I have to be careful in dropping elements. I must work from the back of the list to the front.

    A response to that post later in the thread states:

    For deleting an element of a list, see R FAQ 7.1

    And the relevant section of the R FAQ says:

    ... Do not set x[i] or x[[i]] to NULL, because this will remove the corresponding component from the list.

    Which seems to tell you (in a somewhat backwards way) how to remove an element.

    Hope that helps, or at least leads you in the right direction.

    0 讨论(0)
  • 2020-11-28 01:53

    You can use which.

    x<-c(1:5)
    x
    #[1] 1 2 3 4 5
    x<-x[-which(x==4)]
    x
    #[1] 1 2 3 5
    
    0 讨论(0)
  • 2020-11-28 01:54

    Using lapply and grep:

    lst <- list(a = 1:4, b = 4:8, c = 8:10)
    # say you want to remove a and c
    toremove<-c("a","c")
    lstnew<-lst[-unlist(lapply(toremove, function(x) grep(x, names(lst)) ) ) ]
    #or
    pattern<-"a|c"
    lstnew<-lst[-grep(pattern, names(lst))]
    
    0 讨论(0)
提交回复
热议问题