1

Here's something odd that the apply functions are doing and I'm wondering if anyone can explain this to me.

If I run the following:

namer <- function(x, y) {
  print(paste0("x is ", x))
  print(paste0("y is ", y))
}
sapply(c(1,2,3), FUN = namer, y = 100)

It outputs:

[1] "x is 1"
[1] "y is 100"
[1] "x is 2"
[1] "y is 100"
[1] "x is 3"
[1] "y is 100"
[1] "y is 100" "y is 100" "y is 100"

Why that last row, which seems to run through the function as many times as I provided x inputs, but only outputting the y input (and all as one row)? This makes working with the output a bit tricky since I will need to somehow omit the final row each time.

Thanks.

scoste
  • 21
  • 3
  • 3
    your function by default returns the last line of the function code. Add return() if you don't want to return anything. (Try assigning the result of `sapply`, you'll only see 6 lines printed and the "last line" will be in the object receiving the result of `sapply`) – Cath Feb 15 '17 at 14:41
  • [this Q&A](http://stackoverflow.com/questions/11738823/explicitly-calling-return-in-a-function-or-not) may help you understand how it works – Cath Feb 15 '17 at 14:49
  • 1
    Interesting, thanks, Cath! I had actually stumbled upon that Q&A before but it's helpful to reread with this issue in mind. Much appreciate the pointer. (By the way, I'd make your comment the answer if it were submitted as one) – scoste Feb 15 '17 at 14:57
  • Also, I appreciate the pointer towards duplicate questions (I was struggling with search terms so didn't find them myself), @frank. What's the etiquette on this—should I delete my question or let it stand with the duplicate tag? – scoste Feb 15 '17 at 15:02
  • 1
    you can leave it here, it will make it easier for others to find answers on the topic – Cath Feb 15 '17 at 15:13

0 Answers0