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

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


当前回答

我根本不懂R,但有点创造性的谷歌搜索把我带到了这里:http://tolstoy.newcastle.edu.au/R/help/05/04/1919.html

关键的一句话是:

我没有找到关于R如何从列表中删除元素的明确文档,但试验和错误告诉我

我的列表[5]<- NULL

将删除第5个元素,然后“关闭”由删除该元素引起的孔。这影响了下标值,所以我在删除元素时要小心。我必须从名单的后面到前面。

帖子后面的回复说:

删除列表中的元素,请参见R FAQ 7.1

R FAQ的相关部分说:

... 不要将x[i]或x[[i]]设置为NULL,因为这将从列表中删除相应的组件。

它似乎(以一种有点倒退的方式)告诉您如何删除一个元素。

其他回答

使用lapply和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))]

你可以用which。

x<-c(1:5)
x
#[1] 1 2 3 4 5
x<-x[-which(x==4)]
x
#[1] 1 2 3 5

在命名列表的情况下,我发现这些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

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

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

使用-(负号)与元素的位置一起,例如,如果要删除第三个元素,则使用your_list[-3]

输入

my_list <- list(a = 3, b = 3, c = 4, d = "Hello", e = NA)
my_list
# $`a`
# [1] 3

# $b
# [1] 3

# $c
# [1] 4

# $d
# [1] "Hello"

# $e
# [1] NA

从列表中删除单个元素

 my_list[-3]
 # $`a`
 # [1] 3

 # $b
 # [1] 3

 # $d
 # [1] "Hello"

 # $e
 [1] NA

从列表中删除多个元素

 my_list[c(-1,-3,-2)]
 # $`d`
 # [1] "Hello"

 # $e
 # [1] NA

 my_list[c(-3:-5)]
 # $`a`
 # [1] 3

 # $b
 # [1] 3

 my_list[-seq(1:2)]
 # $`c`
 # [1] 4

 # $d
 # [1] "Hello"

 # $e
 # [1] NA