我有一个列表,我想从其中删除一个元素。我该怎么做呢?

我试着在参考手册中查找我认为这个函数的明显名称,但我没有找到任何合适的名称。


当前回答

这个怎么样?还是使用下标

> m <- c(1:5)
> m
[1] 1 2 3 4 5

> m[1:length(m)-1]
[1] 1 2 3 4

or

> m[-(length(m))]
[1] 1 2 3 4

其他回答

这个怎么样?还是使用下标

> m <- c(1:5)
> m
[1] 1 2 3 4 5

> m[1:length(m)-1]
[1] 1 2 3 4

or

> m[-(length(m))]
[1] 1 2 3 4

还可以使用magrittr包的提取函数从列表中进行负索引以删除列表项。

a <- seq(1,5)
b <- seq(2,6)
c <- seq(3,7)
l <- list(a,b,c)

library(magrittr)

extract(l,-1) #simple one-function method
[[1]]
[1] 2 3 4 5 6

[[2]]
[1] 3 4 5 6 7

如果您想避免数字索引,可以使用

a <- setdiff(names(a),c("name1", ..., "namen"))

从a中删除名字namea…namen,这适用于列表

> l <- list(a=1,b=2)
> l[setdiff(names(l),"a")]
$b
[1] 2

对于向量也是一样

> v <- c(a=1,b=2)
> v[setdiff(names(v),"a")]
b 
2

在命名列表的情况下,我发现这些helper函数很有用

member <- function(list,names){
    ## return the elements of the list with the input names
    member..names <- names(list)
    index <- which(member..names %in% names)
    list[index]    
}


exclude <- function(list,names){
     ## return the elements of the list not belonging to names
     member..names <- names(list)
     index <- which(!(member..names %in% names))
    list[index]    
}  
aa <- structure(list(a = 1:10, b = 4:5, fruits = c("apple", "orange"
)), .Names = c("a", "b", "fruits"))

> aa
## $a
##  [1]  1  2  3  4  5  6  7  8  9 10

## $b
## [1] 4 5

## $fruits
## [1] "apple"  "orange"


> member(aa,"fruits")
## $fruits
## [1] "apple"  "orange"


> exclude(aa,"fruits")
## $a
##  [1]  1  2  3  4  5  6  7  8  9 10

## $b
## [1] 4 5

不知道你是否还需要回答这个问题,但我从我有限的(3周的自学R) R经验中发现,使用NULL赋值实际上是错误的或次优的,特别是当你在动态更新一个列表时,比如for循环。

更准确地说,使用

myList[[5]] <- NULL

会抛出错误

myList[[5]] <- NULL:替换长度为0

or

供应的元素多于可供替换的元素

我发现更有效的方法是

myList <- myList[[-5]]