How can I delete component from list in R?

前端 未结 4 1536
面向向阳花
面向向阳花 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.

提交回复
热议问题