For my function to perform well I need to get the class object of multiple objects that meet the following condition:
- The first class sends
TRUE
when the object is all three:list, character, character
. - 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?
Updated with @Akruns answer:
test_class_object <- function(class_object) {
if(is(class_object,'list') == TRUE){
if ({
c(class(class_object), sapply(class_object, function(x)class(x)[1]))%>% last() == 'character'
} ){print('all characters')} else if(
{
c(class(class_object), sapply(class_object, function(x)class(x)[1]))%>% last() == 'numeric'
}
){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.
CodePudding user response:
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