我有一个列表,我想从其中删除一个元素。我该怎么做呢?
我试着在参考手册中查找我认为这个函数的明显名称,但我没有找到任何合适的名称。
我有一个列表,我想从其中删除一个元素。我该怎么做呢?
我试着在参考手册中查找我认为这个函数的明显名称,但我没有找到任何合适的名称。
当前回答
这里有一个简单的解决方案,可以使用底数r。它从原始的数字列表中删除数字5。您可以使用相同的方法从列表中删除任何您想要的元素。
#the original list
original_list = c(1:10)
#the list element to remove
remove = 5
#the new list (which will not contain whatever the `remove` variable equals)
new_list = c()
#go through all the elements in the list and add them to the new list if they don't equal the `remove` variable
counter = 1
for (n in original_list){
if (n != ){
new_list[[counter]] = n
counter = counter + 1
}
}
new_list变量不再包含5。
new_list
# [1] 1 2 3 4 6 7 8 9 10
其他回答
你可以用which。
x<-c(1:5)
x
#[1] 1 2 3 4 5
x<-x[-which(x==4)]
x
#[1] 1 2 3 5
不知道你是否还需要回答这个问题,但我从我有限的(3周的自学R) R经验中发现,使用NULL赋值实际上是错误的或次优的,特别是当你在动态更新一个列表时,比如for循环。
更准确地说,使用
myList[[5]] <- NULL
会抛出错误
myList[[5]] <- NULL:替换长度为0
or
供应的元素多于可供替换的元素
我发现更有效的方法是
myList <- myList[[-5]]
这个怎么样?还是使用下标
> 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
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