10

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
Community
  • 1
  • 1
Ken Benoit
  • 14,454
  • 27
  • 50
  • 5
    No, that's not possible with vapply. If you want checks write a function that includes them. – Roland Mar 15 '17 at 19:00

1 Answers1

0

sapply is unsafe because its return type is not stable. If you know your return type you can safely use vapply. If not, like in your case, simply use lapply instead.

For your example:

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)

lapply(list_12, names) # always list() return type
Andre Wildberg
  • 12,344
  • 3
  • 12
  • 29