One option is to use the is()
function that is more generic than is.integer
, for example. It requires, as the second argument the class to be checked.
Placing the result of the mget(ls())
proposed in the question within a list can be useful in avoiding to be recreating the list at each iteration of the function.
ambiente <- mget(ls())
So we could have a function that returns the name of the objects of a list that are of certain class.
filtrar_classe <- function(classe, lista) {
names(Filter(function(x) is(x, classe), lista))
}
Once the function is defined, we can apply it to the desired classes
classes <- c("list", "integer")
res <- classes %>%
lapply(filtrar_classe, lista = ambiente) %>%
unlist()
res
# [1] "e" "f" "a" "b"
Now that we have a vector of characters as an answer, we can pass its result as argument to the function rm()
.
rm(list = res)
ls()
# [1] "ambiente" "c" "classes" "d"
# [5] "filtrar_classe" "g" "h" "res"
tidyverse
If we want to leave the solution more "tidy", we can do as follows
filtrar_tidy <- function(classe, lista) {
keep(lista, ~ is(.x, classe)) %>%
names()
}
classes %>%
map(filtrar_tidy, lista = ambiente) %>%
flatten_chr()
About the option in the list
The idea is the same, just use the names together with [
to select the elements of the list you want to delete.
nova_lista <- ambiente[ !names(ambiente) %in% res ]
nova_lista
$c
[1] "a"
$d
[1] "a"
$g
[1] 1.1
$h
[1] 1.1