Remove elements from a list that have part of a character or that are of a certain class

2

Consider the list:

mylist=structure(list(quem = 1:10, quer = c(1.1, 2.1, 3.1, 4.1, 5.1), 
isso = structure(list(X__1 = c(1, 2, 3, 4, 5, 6, 7, 8, 9, 
10, 11, 12), X__2 = c(123, 456, 789, 1122, NA, 1788, NA, 
2454, 2787, NA, 3453, 3786), X__3 = c("a", NA, "a", NA, NA, 
"a", "a", NA, "a", "a", "b", "b")), .Names = c("X__1", "X__2", 
"X__3"), row.names = c(NA, -12L), class = "data.frame")), .Names = 
c("quem", 
"quer", "isso"))

Objective 1 : remove elements of mylist that contain the particle qu

Goal 2 : remove elements from mylist that are of class data.frame

These objectives are mutually exclusive. That is, each goal must have a function.

    
asked by anonymous 04.12.2018 / 04:10

2 answers

4

Goal 1: remove mylist elements that contain the particle qu

mylist[grep("qu", names(mylist))]

Just do a regular expression and look for the term qu . Note that the output is also a lista

Goal 2: remove mylist elements that are from the data.frame class

mylist[sapply(mylist, is.data.frame)]

Note that the output is also a lista

    
04.12.2018 / 12:29
4

Here are two functions.

Goal 1

qu_extract <- function(object){
  if(!inherits(object, "list")){
    obj <- deparse(substitute(object))
    stop(paste(obj, "não é de classe 'list'"))
  }
  inx <- sapply(names(object), function(x) grepl("qu", x))
  if(any(inx)) object[inx] else invisible(NULL)
}


qu_extract(mylist)
#$quem
#[1]  1  2  3  4  5  6  7  8  9 10
#
#$quer
#[1] 1.1 2.1 3.1 4.1 5.1

y <- 1:5
qu_extract(y)
#Error in qu(y) : y não é de classe 'list'

Goal 2.

df_extract <- function(object){
  inx <- sapply(object, inherits, "data.frame")
  if(any(inx)) object[inx] else invisible(NULL)
}

df_extract(mylist)
df_extract(y)
    
04.12.2018 / 12:40