我有一个列表,我想从其中删除一个元素。我该怎么做呢?
我试着在参考手册中查找我认为这个函数的明显名称,但我没有找到任何合适的名称。
我有一个列表,我想从其中删除一个元素。我该怎么做呢?
我试着在参考手册中查找我认为这个函数的明显名称,但我没有找到任何合适的名称。
当前回答
在命名列表的情况下,我发现这些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)]
处理列表和向量
单行从列表中删除Null元素:
x = x(((酸式焦磷酸钠(x, is.null) arr.ind = TRUE)))
干杯
这个怎么样?还是使用下标
> 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
我想补充的是,如果它是一个命名列表,你可以简单地使用。
l <- list(a = 1, b = 2)
> within(l, rm(a))
$b
[1] 2
所以你可以覆盖原来的列表
l <- within(l, rm(a))
从列表l中删除名为a的元素。
如果你不想就地修改列表(例如,将一个元素传递给一个函数),你可以使用索引:负索引表示“不包括这个元素”。
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