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

Asked

Viewed 61 times

1

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: withdraw elements of mylist containing the particle qu

Objective 2: withdraw elements of mylist class data.frame

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

2 answers

3


Objective 1: remove Mylist elements containing 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

Objective 2: remove elements of Mylist that are of the data class.frame

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

Note that the output is also a lista

3

Here are two functions.

Objective 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'

Objective 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)

Browser other questions tagged

You are not signed in. Login or sign up in order to post.