我有一个列表,我想从其中删除一个元素。我该怎么做呢?
我试着在参考手册中查找我认为这个函数的明显名称,但我没有找到任何合适的名称。
我有一个列表,我想从其中删除一个元素。我该怎么做呢?
我试着在参考手册中查找我认为这个函数的明显名称,但我没有找到任何合适的名称。
当前回答
purrr包中有几个选项没有被提到:
Pluck和assign_in可以很好地使用嵌套值,你可以使用名称和/或索引的组合来访问它:
library(purrr)
l <- list("a" = 1:2, "b" = 3:4, "d" = list("e" = 5:6, "f" = 7:8))
# select values (by name and/or index)
all.equal(pluck(l, "d", "e"), pluck(l, 3, "e"), pluck(l, 3, 1))
[1] TRUE
# or if element location stored in a vector use !!!
pluck(l, !!! as.list(c("d", "e")))
[1] 5 6
# remove values (modifies in place)
pluck(l, "d", "e") <- NULL
# assign_in to remove values with name and/or index (does not modify in place)
assign_in(l, list("d", 1), NULL)
$a
[1] 1 2
$b
[1] 3 4
$d
$d$f
[1] 7 8
或者你可以通过分配zap()或NULL使用modify_list删除值:
all.equal(list_modify(l, a = zap()), list_modify(l, a = NULL))
[1] TRUE
你可以使用带有discard和keep的谓词函数来删除或保留元素:
# remove numeric elements
discard(l, is.numeric)
$d
$d$e
[1] 5 6
$d$f
[1] 7 8
# keep numeric elements
keep(l, is.numeric)
$a
[1] 1 2
$b
[1] 3 4
其他回答
只是想快速添加(因为我在任何答案中都没有看到它),对于一个命名列表,你也可以做l["name"] <- NULL。例如:
l <- list(a = 1, b = 2, cc = 3)
l['b'] <- NULL
你可以用which。
x<-c(1:5)
x
#[1] 1 2 3 4 5
x<-x[-which(x==4)]
x
#[1] 1 2 3 5
使用-(负号)与元素的位置一起,例如,如果要删除第三个元素,则使用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
在命名列表的情况下,我发现这些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
单行从列表中删除Null元素:
x = x(((酸式焦磷酸钠(x, is.null) arr.ind = TRUE)))
干杯