2013-03-27 92 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) 

是寫這的整潔,功能,途徑。