0

Recently our lecturer taught us about the apply family in R. As I was reviewing my notes I was puzzled on one part regarding the application of sapply versus vapply as the lecturer indicated they are essentially the same.

My understanding of sapply is that it attempts to simplify the argument it is provided and return this to the user. However, it doesn't always return a simplified value due to the input vector being of a variable length (I didn't fully understand this point). However, sapply won't point this out.

With vapply however, you don't run the risk of having a vector fail to be simplified without you knowing as it will throw an error message if this is the case and you have to specify a return type value.

In that case, my understanding would be that vapply would be the preferred option over sapply as it is the safer option. I asked my tutor if this was the case and he said it all came down to personal preference.

Is this truly the case - that vapply and sapply are inherently the same function except one is more fail-safe than the other? Or are there certain situation(s) where you would want to explicitly use vapply over sapply and vice versa?

I have read the following SO which has helped shed some light on the differences from a performance perspective: Why is `vapply` safer than `sapply`?

Edit: I have re-read the why-is-vapply-safer-than-sapply link but I don't think I'm fully across this. My question still stands in that, Is there a situation where sapply would be more suitable than vapply? Does such a situation exist?

Thank you.

IronKirby
  • 708
  • 1
  • 7
  • 24
  • 2
    I think the answer to your question can be found here: https://stackoverflow.com/questions/12339650/why-is-vapply-safer-than-sapply Hope this helps! – Florian Jul 15 '17 at 08:19
  • Hi azurekirby, as your question stands now, it's really a duplicate of that one. If you think that your real question is not answered yet, please edit and rephrase your question to highlight the difference from the other one, tag me, and I'll vote to reopen the question. Also check out this one for other apply variations : https://stackoverflow.com/questions/3505701/r-grouping-functions-sapply-vs-lapply-vs-apply-vs-tapply-vs-by-vs-aggrega – Joris Meys Jul 15 '17 at 08:36
  • @JorisMeys: Hi Joris, this is perfect (https://stackoverflow.com/questions/3505701/r-grouping-functions-sapply-vs-lapply-vs-apply-vs-tapply-vs-by-vs-aggrega). Exactly what I was after :). Happy to have this closed. – IronKirby Jul 15 '17 at 10:07
  • Use sapply when you use R interactively, use vapply when writing code that you want to reuse or give to others. – Roland Jul 15 '17 at 14:51

0 Answers0