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
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)
Filter(is.numeric, tempList)
is a tidy, functional, way of writing this.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With