Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Get class objects of multiple objects

For my function to perform well I need to get the class object of multiple objects that meet the following condition:

  1. The first class sends TRUE when the object is all three: list, character, character.
  2. The second class should send TRUE when the object is all three: list, character, numeric.

For example:

first_class <- list('prediction','median')
second_class <- list('prediction', c(1, 2, 3, 4))

test_class_object <- function(class_object) {
  if (is(class_object, 'list') == TRUE &
      is(class_object[[1]], 'character') == TRUE &
      is(class_object[[2]], 'character') == TRUE) {
    print('all characters')
  } else if (is(class_object, 'list') == TRUE &
             is(class_object[[1]], 'character') == TRUE &
             is(class_object[[2]], 'numeric') == TRUE) {
    print('last is numeric')
  }
}

Whilst this works ok for small number of objects, if I had a larger list of objects like 15 then this would be very messy. How can I in the most simplest form repeat this function?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

Updated with @Akruns answer:

test_class_object <- function(class_object) {
    if(is(class_object,'list') == TRUE){
      if ({
        c(class(class_object), sapply(class_object, class))%>% last() %>%  is(., 'character')
      } == TRUE){print('all characters')} else if(
        {
          c(class(class_object), sapply(class_object, class))%>% last() %>%  is(., 'numeric')
        } == TRUE
      ){print('last is numeric')} else print('not found')
    }else {
      stop("You need a list object, for example: list('prediction','median)")
    }

This allows for more mobility, I’ll also have to check into @r2Evans comment because as it stands my lists have single class objects, but I may get multiples in the near future.

>Solution :

If we want to get the class of inner list elements, use lapply/sapply to get the class i.e.

c(class(first_class), sapply(first_class, class))

returns a vector

c(class(first_class), lapply(first_class, class))

returns a list, then can use a vector of class values to compare

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading