我有一个列表,我想从其中删除一个元素。我该怎么做呢?
我试着在参考手册中查找我认为这个函数的明显名称,但我没有找到任何合适的名称。
我有一个列表,我想从其中删除一个元素。我该怎么做呢?
我试着在参考手册中查找我认为这个函数的明显名称,但我没有找到任何合适的名称。
当前回答
如果你有一个命名列表,想要删除一个特定的元素,你可以尝试:
lst <- list(a = 1:4, b = 4:8, c = 8:10)
if("b" %in% names(lst)) lst <- lst[ - which(names(lst) == "b")]
这将创建一个包含元素a, b, c的列表lst。第二行在检查元素b是否存在后删除元素b(以避免@hjv提到的问题)。
或更好:
lst$b <- NULL
这样,尝试删除一个不存在的元素就不是问题(例如lst$g <- NULL)
其他回答
这里有一个简单的解决方案,可以使用底数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
如果您想避免数字索引,可以使用
a <- setdiff(names(a),c("name1", ..., "namen"))
从a中删除名字namea…namen,这适用于列表
> l <- list(a=1,b=2)
> l[setdiff(names(l),"a")]
$b
[1] 2
对于向量也是一样
> v <- c(a=1,b=2)
> v[setdiff(names(v),"a")]
b
2
单行从列表中删除Null元素:
x = x(((酸式焦磷酸钠(x, is.null) arr.ind = TRUE)))
干杯
如果你有一个命名列表,想要删除一个特定的元素,你可以尝试:
lst <- list(a = 1:4, b = 4:8, c = 8:10)
if("b" %in% names(lst)) lst <- lst[ - which(names(lst) == "b")]
这将创建一个包含元素a, b, c的列表lst。第二行在检查元素b是否存在后删除元素b(以避免@hjv提到的问题)。
或更好:
lst$b <- NULL
这样,尝试删除一个不存在的元素就不是问题(例如lst$g <- NULL)
这个怎么样?还是使用下标
> 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