I am trying to follow good practice and use vapply()
instead of sapply()
inside functions, but find the type checking from vapply()
to be too inflexible when wanting a fixed length.
Let's say I want something like this:
list1 <- list(l1_one = 1:3, l1_two = letters[1:3])
list2 <- list(l2_one = 4:6, l2_two = letters[4:6], l2_three = 10:12)
list_12 <- list(list1, list2)
sapply(list_12, names)
# [[1]]
# [1] "l1_one" "l1_two"
#
# [[2]]
# [1] "l2_one" "l2_two" "l2_three"
Is there a way to allow variable lengths, but check that the return is of mode "character", and at least one in length? Clearly this does not work:
vapply(list_12, names, character(2))
# Error in vapply(list_12, names, character(2)) : values must be length 2,
# but FUN(X[[2]]) result is length 3