我有一个列表,我想从其中删除一个元素。我该怎么做呢?
我试着在参考手册中查找我认为这个函数的明显名称,但我没有找到任何合适的名称。
我有一个列表,我想从其中删除一个元素。我该怎么做呢?
我试着在参考手册中查找我认为这个函数的明显名称,但我没有找到任何合适的名称。
当前回答
如果你不想就地修改列表(例如,将一个元素传递给一个函数),你可以使用索引:负索引表示“不包括这个元素”。
x <- list("a", "b", "c", "d", "e"); # example list
x[-2]; # without 2nd element
x[-c(2, 3)]; # without 2nd and 3rd
同样,逻辑索引向量也很有用:
x[x != "b"]; # without elements that are "b"
这也适用于数据框架:
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
其他回答
rlist包(http://cran.r-project.org/web/packages/rlist/index.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"))
结果:
# $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
不知道你是否还需要回答这个问题,但我从我有限的(3周的自学R) R经验中发现,使用NULL赋值实际上是错误的或次优的,特别是当你在动态更新一个列表时,比如for循环。
更准确地说,使用
myList[[5]] <- NULL
会抛出错误
myList[[5]] <- NULL:替换长度为0
or
供应的元素多于可供替换的元素
我发现更有效的方法是
myList <- myList[[-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
下面是如何在R中删除列表的最后一个元素:
x <- list("a", "b", "c", "d", "e")
x[length(x)] <- NULL
如果x可能是一个向量,那么你需要创建一个新对象:
x <- c("a", "b", "c", "d", "e")
x <- x[-length(x)]
处理列表和向量
这里有一个简单的解决方案,可以使用底数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