gpt4 book ai didi

从 R 列表中删除特定类的元素

转载 作者:行者123 更新时间:2023-12-01 00:42:36 25 4
gpt4 key购买 nike

我希望有一个简单的方法可以做到这一点,但搜索后找不到答案。我有一个列表,想要删除特定类的元素。

例如说我有列表

tempList <- list(2,4,'a', 7, 'f')

如何删除所有字符条目,只留下 2、4 和 7 的列表。

提前致谢

最佳答案

尝试

> tempList[!sapply(tempList, function(x) class(x) == "character")]
[[1]]
[1] 2

[[2]]
[1] 4

[[3]]
[1] 7

请注意,这是等效的。

tempList[sapply(tempList, function(x) class(x) != "character")]

如果你需要经常使用它,你可以将它做成一个函数。

classlist <- function(x) {
sapply(x, class)
}

tempList[classlist(tempList) != "character"]

classlist2 <- function(x) {
x[!sapply(x, function(m) class(m) == "character")]
}

classlist2(tempList)

关于从 R 列表中删除特定类的元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15659323/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com