Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Remove element of specific class from list in R

I expect there is a simple way to do this but after searching couldn't find an answer. I have a list and want to remove elements of a specific class.

For example say I have the list

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

How could I remove all character entries to just leave a list of 2, 4 and 7.

Thanks in advance

like image 234
user1165199 Avatar asked Dec 20 '22 08:12

user1165199


2 Answers

Try

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

[[2]]
[1] 4

[[3]]
[1] 7

Note that this is equivalent.

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

If you need to use this a lot, you can make it into a function.

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

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

or

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

classlist2(tempList)
like image 69
Roman Luštrik Avatar answered Jan 18 '23 12:01

Roman Luštrik


Filter(is.numeric, tempList)

is a tidy, functional, way of writing this.

like image 42
Martin Morgan Avatar answered Jan 18 '23 11:01

Martin Morgan