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.
我已经试过了,我认为这个函数的明显名称应该在参考手册中,我还没有找到合适的。
12 个解决方案
#1
160
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://托尔斯泰。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
关于如何从列表中删除元素,我没有找到关于R的显式文档,但是尝试和错误告诉我。
myList[[5]] <- NULL
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.
将删除第5个元素,然后“关闭”该元素所造成的漏洞。这就满足了索引值,所以我必须小心删除元素。我必须从名单的后面到前线工作。
A response to that post later in the thread states:
稍后在线程状态中对该post的响应:
For deleting an element of a list, see R FAQ 7.1
要删除列表中的元素,请参见R FAQ 7.1。
And the relevant section of the R FAQ says:
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.
希望这能有所帮助,或者至少引导你走向正确的方向。
#2
152
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:
这也适用于dataframes:
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
#3
25
Here is how the remove the last element of a list in 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 lists and vectors
- 为列表和向量工作。
#4
16
Removing Null elements from a list in single line :
从单行中删除列表中的Null元素:
x=x[-(which(sapply(x,is.null),arr.ind=TRUE))]
x = x(((酸式焦磷酸钠(x,is.null)arr.ind = TRUE)))
Cheers
干杯
#5
10
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 lst
with elements a
, b
, c
. The second line removes element b
after it checks that it exists (to avoid the problem @hjv mentioned).
这将使用元素a、b、c列出清单1。第二行删除元素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)
#6
6
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
#7
6
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 NULL
assignment is actually wrong or sub-optimal especially if you're dynamically updating a list in something like a for-loop.
不知道您是否还需要一个答案,但是我从我有限的(3周的自学R)经验中发现,使用NULL赋值实际上是错误的或者是次优化的,特别是当你在一个for循环中动态更新一个列表时。
To be more precise, using
更确切地说,使用。
myList[[5]] <- NULL
will throw the error
将抛出错误
myList[[5]] <- NULL : replacement has length zero
myList[[5]] <- NULL:替换长度为0。
or
或
more elements supplied than there are to replace
提供的元素多于替换的元素。
What I found to work more consistently is
我发现工作更一致的是!
myList <- myList[[-5]]
#8
1
In the case of named lists I find those helper functions useful
在命名列表的情况下,我发现这些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
#9
0
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
#10
0
Using lapply and grep:
使用拉普和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))]
#11
-1
How about this? Again, using indices
这个怎么样?再次,使用指数
> 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
#12
-2
You can use which
.
您可以使用。
x<-c(1:5)
x
#[1] 1 2 3 4 5
x<-x[-which(x==4)]
x
#[1] 1 2 3 5
#1
160
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://托尔斯泰。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
关于如何从列表中删除元素,我没有找到关于R的显式文档,但是尝试和错误告诉我。
myList[[5]] <- NULL
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.
将删除第5个元素,然后“关闭”该元素所造成的漏洞。这就满足了索引值,所以我必须小心删除元素。我必须从名单的后面到前线工作。
A response to that post later in the thread states:
稍后在线程状态中对该post的响应:
For deleting an element of a list, see R FAQ 7.1
要删除列表中的元素,请参见R FAQ 7.1。
And the relevant section of the R FAQ says:
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.
希望这能有所帮助,或者至少引导你走向正确的方向。
#2
152
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:
这也适用于dataframes:
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
#3
25
Here is how the remove the last element of a list in 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 lists and vectors
- 为列表和向量工作。
#4
16
Removing Null elements from a list in single line :
从单行中删除列表中的Null元素:
x=x[-(which(sapply(x,is.null),arr.ind=TRUE))]
x = x(((酸式焦磷酸钠(x,is.null)arr.ind = TRUE)))
Cheers
干杯
#5
10
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 lst
with elements a
, b
, c
. The second line removes element b
after it checks that it exists (to avoid the problem @hjv mentioned).
这将使用元素a、b、c列出清单1。第二行删除元素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)
#6
6
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
#7
6
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 NULL
assignment is actually wrong or sub-optimal especially if you're dynamically updating a list in something like a for-loop.
不知道您是否还需要一个答案,但是我从我有限的(3周的自学R)经验中发现,使用NULL赋值实际上是错误的或者是次优化的,特别是当你在一个for循环中动态更新一个列表时。
To be more precise, using
更确切地说,使用。
myList[[5]] <- NULL
will throw the error
将抛出错误
myList[[5]] <- NULL : replacement has length zero
myList[[5]] <- NULL:替换长度为0。
or
或
more elements supplied than there are to replace
提供的元素多于替换的元素。
What I found to work more consistently is
我发现工作更一致的是!
myList <- myList[[-5]]
#8
1
In the case of named lists I find those helper functions useful
在命名列表的情况下,我发现这些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
#9
0
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
#10
0
Using lapply and grep:
使用拉普和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))]
#11
-1
How about this? Again, using indices
这个怎么样?再次,使用指数
> 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
#12
-2
You can use which
.
您可以使用。
x<-c(1:5)
x
#[1] 1 2 3 4 5
x<-x[-which(x==4)]
x
#[1] 1 2 3 5