How can I delete component from list in R?

前端 未结 4 1537
面向向阳花
面向向阳花 2021-01-21 08:23

I am trying to remove a component from list in R, but it is not working.

I have list like this:

> myList
[[1]]
[[1]][[1]]
[1] \"Sunny\"  \"Cloudy\" \"         


        
相关标签:
4条回答
  • 2021-01-21 08:28

    Assigning a list member to NULL is a standard way of removing list items. For named lists, it can be the most straightforward way of doing it. e.g.

    myList <- list(a = list(x = 1, y = 2), b = list(d = 3, e = 4))
    myList$a$y <- NULL
    myList$b <- NULL
    myList[["a"]] <- NULL
    

    It works with data.frames as well (which are just a special type of list).

    Occasionally this can cause confusing behaviour. For example:

    x <- as.list(LETTERS[1:10])
    fn <- function(y) if(y == 7) NULL else y
    for (i in 1:10) x[[i]] <- fn(i)
    

    Expected contents of x[[7]] might be NULL, but it's actually "H". Assigning NULL to x[[7]] deletes the list member shifting x[[8]] down.

    0 讨论(0)
  • 2021-01-21 08:29

    I think it's because you're lists are so heavily nested. I attempted to replicate your data and could using:

    (x <- list(c(list(c(1)),list(c(10:15)),list(c(2))),c(list(c(1:4)), list(c(3:5)))))
    

    I don't know if having a list this heavily nested is intentional or not but this may be where a great deal of your problems lie. You could try assigning NULL to the "components" as in:

    x[[1]][[1]][[1]] <- NULL
    
    0 讨论(0)
  • 2021-01-21 08:32

    I think you came very close to the right answer:

    > x <- list(list(1:3, 4:6), list(4:7, 2:3), list(4:6,1:2))
    > x[-2]
    [[1]]
    [[1]][[1]]
    [1] 1 2 3
    
    [[1]][[2]]
    [1] 4 5 6
    
    
    [[2]]
    [[2]][[1]]
    [1] 4 5 6
    
    [[2]][[2]]
    [1] 1 2
    

    The above works to get rid of the original second component. Note single square brackets, and compare with:

    x[[-2]]

    Error in x[[-2]] : attempt to select more than one element
    

    Double squrare brackets do not work. (Actually that does work if there are only two compoennts in the list, but do not depend on that.)

    There are numerous places that explain single versus double square brackets. One of them is Circle 8.1.54 of 'The R Inferno' http://www.burns-stat.com/pages/Tutor/R_inferno.pdf

    0 讨论(0)
  • 2021-01-21 08:51

    You could get rid of multiple rows with a list of 220 elements lets say list[-c(69,213,214,215,216)], for a list of two list <- list[-c(1,2)]. Remember to put in as.matrix.

    0 讨论(0)
提交回复
热议问题