list 如何从列表中删除元素?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/652136/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-11 01:20:28  来源:igfitidea点击:

How can I remove an element from a list?

rlistindexing

提问by David Locke

I have a list and I want to remove a single element from it. How can I do this?

我有一个列表,我想从中删除一个元素。我怎样才能做到这一点?

I've tried looking up what I think the obvious names for this function would be in the reference manual and I haven't found anything appropriate.

我已经尝试在参考手册中查找我认为此函数的明显名称,但我没有找到任何合适的内容。

采纳答案by Chad Birch

I don't know R at all, but a bit of creative googling led me here: http://tolstoy.newcastle.edu.au/R/help/05/04/1919.html

我根本不知道 R,但是一些创造性的谷歌搜索使我来到这里: http://tolstoy.newcastle.edu.au/R/help/05/04/1919.html

The key quote from there:

那里的关键引述:

I do not find explicit documentation for R on how to remove elements from lists, but trial and error tells me

myList[[5]] <- NULL

will remove the 5th element and then "close up" the hole caused by deletion of that element. That suffles the index values, So I have to be careful in dropping elements. I must work from the back of the list to the front.

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

myList[[5]] <- NULL

将删除第 5 个元素,然后“关闭”由删除该元素引起的空洞。这会改变索引值,所以我必须小心删除元素。我必须从列表的后面到前面工作。

A response to that post later in the threadstates:

线程稍后对该帖子回复指出:

For deleting an element of a list, see R FAQ 7.1

要删除列表的元素,请参阅 R FAQ 7.1

And the relevant section of the R FAQsays:

R FAQ相关部分说:

... Do not set x[i] or x[[i]] to NULL, because this will remove the corresponding component from the list.

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

Which seems to tell you (in a somewhat backwards way) how to remove an element.

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

Hope that helps, or at least leads you in the right direction.

希望这会有所帮助,或者至少可以引导您朝着正确的方向前进。

回答by Florian Jenn

If you don't want to modify the list in-place (e.g. for passing the list with an element removed to a function), you can use indexing: negative indices mean "don't include this element".

如果您不想就地修改列表(例如,将删除元素的列表传递给函数),您可以使用索引:负索引表示“不包含此元素”。

x <- list("a", "b", "c", "d", "e"); # example list

x[-2];       # without 2nd element

x[-c(2, 3)]; # without 2nd and 3rd

Also, logical index vectors are useful:

此外,逻辑索引向量也很有用:

x[x != "b"]; # without elements that are "b"

This works with dataframes, too:

这也适用于数据帧:

df <- data.frame(number = 1:5, name = letters[1:5])

df[df$name != "b", ];     # rows without "b"

df[df$number %% 2 == 1, ] # rows with odd numbers only

回答by Aleksandr Levchuk

Here is how the remove the last element of a listin R:

下面是如何在 R 中删除列表的最后一个元素:

x <- list("a", "b", "c", "d", "e")
x[length(x)] <- NULL

If x might be a vector then you would need to create a new object:

如果 x 可能是一个向量,那么你需要创建一个新对象:

x <- c("a", "b", "c", "d", "e")
x <- x[-length(x)]
  • Work for listsand vectors
  • 列表向量工作

回答by Sukhi

Removing Null elements from a list in single line :

从单行列表中删除空元素:

x=x[-(which(sapply(x,is.null),arr.ind=TRUE))]

x=x[-(which(sapply(x,is.null),arr.ind=TRUE))]

Cheers

干杯

回答by alko989

If you have a named list and want to remove a specific element you can try:

如果您有一个命名列表并想要删除特定元素,您可以尝试:

lst <- list(a = 1:4, b = 4:8, c = 8:10)

if("b" %in% names(lst)) lst <- lst[ - which(names(lst) == "b")]

This will make a list lstwith elements a, b, c. The second line removes element bafter it checks that it exists (to avoid the problem @hjv mentioned).

这将创建一个lst包含元素a, b,的列表c。第二行在b检查元素存在后删除元素(以避免@hjv 提到的问题)。

or better:

或更好:

lst$b <- NULL

This way it is not a problem to try to delete a non-existent element (e.g. lst$g <- NULL)

这样,尝试删除不存在的元素(例如lst$g <- NULL)不是问题

回答by Kim

I would like to add that if it's a named listyou can simply use within.

我想补充一点,如果它是一个命名列表,您可以简单地使用within.

l <- list(a = 1, b = 2)    
> within(l, rm(a))
$b
[1] 2

So you can overwrite the original list

所以你可以覆盖原始列表

l <- within(l, rm(a)) 

to remove element named afrom list l.

删除a从 list命名的元素l

回答by user2030503

There's the rlist package (http://cran.r-project.org/web/packages/rlist/index.html) to deal with various kinds of list operations.

有 rlist 包 ( http://cran.r-project.org/web/packages/rlist/index.html) 来处理各种列表操作。

Example (http://cran.r-project.org/web/packages/rlist/vignettes/Filtering.html):

示例(http://cran.r-project.org/web/packages/rlist/vignettes/Filtering.html):

library(rlist)
devs <- 
  list(
    p1=list(name="Ken",age=24,
      interest=c("reading","music","movies"),
      lang=list(r=2,csharp=4,python=3)),
    p2=list(name="James",age=25,
      interest=c("sports","music"),
      lang=list(r=3,java=2,cpp=5)),
    p3=list(name="Penny",age=24,
      interest=c("movies","reading"),
      lang=list(r=1,cpp=4,python=2)))

list.remove(devs, c("p1","p2"))

Results in:

结果是:

# $p3
# $p3$name
# [1] "Penny"
# 
# $p3$age
# [1] 24
# 
# $p3$interest
# [1] "movies"  "reading"
# 
# $p3$lang
# $p3$lang$r
# [1] 1
# 
# $p3$lang$cpp
# [1] 4
# 
# $p3$lang$python
# [1] 2

回答by user2035799

Don't know if you still need an answer to this but I found from my limited (3 weeks worth of self-teaching R) experience with R that, using the NULLassignment is actually wrong or sub-optimal especially if you're dynamically updating a list in something like a for-loop.

不知道您是否仍然需要对此的答案,但我从我有限的(3 周的自学 R)经验中发现,使用 RNULL分配实际上是错误的或次优的,尤其是如果您正在动态更新类似于 for 循环的列表。

To be more precise, using

更准确地说,使用

myList[[5]] <- NULL

will throw the error

会抛出错误

myList[[5]] <- NULL : replacement has length zero

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

or

或者

more elements supplied than there are to replace

提供的元素多于需要替换的元素

What I found to work more consistently is

我发现更一致的工作是

myList <- myList[[-5]]

回答by Sowmya S. Manian

Use -(Negative sign) along with position of element, example if 3rd element is to be removed use it as your_list[-3]

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

Input

输入

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

Remove single element from list

从列表中删除单个元素

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

 # $b
 # [1] 3

 # $d
 # [1] "Hello"

 # $e
 [1] NA

Remove multiple elements from list

从列表中删除多个元素

 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

回答by Alexey Shiklomanov

Just wanted to quickly add (because I didn't see it in any of the answers) that, for a named list, you can also do l["name"] <- NULL. For example:

只是想快速添加(因为我没有在任何答案中看到它),对于命名列表,您也可以执行l["name"] <- NULL. 例如:

l <- list(a = 1, b = 2, cc = 3)
l['b'] <- NULL