2013-03-27 76 views
1

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

例如说我有表

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

我怎么能删除所有角色条目见好就收提前2个,4个和7

感谢名单

回答

5

尝试

> 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) 
+2

即将发布。 – Arun 2013-03-27 12:57:45

2
Filter(is.numeric, tempList) 

是写这的整洁,功能,途径。