Apply functions that return NULL?

lapply(list(1, "a", TRUE), str)

This call actually returns a list, the same size as the input list, containing all NULL values. On the other hand calling

str(TRUE)

on its own prints only the structure of the logical to the console, not NULL . That's because [ str() ] uses [ invisible() ] behind the scenes, which returns an invisible copy of the return value, NULL in this case. This prevents it from being printed when the result of str() is not assigned.

Sorry, I cannot understand the explanation here on DataCamp. Can anyone give me an easy explanation?

This behavior is known as a function's "side-effect". It may be easier to understand with a more relatable example.

my_plot <- plot(iris$Sepal.Length, iris$Sepal.Width)

Created on 2020-07-26 by the reprex package (v0.3.0)

If you type this into RStudio, you will see an object called my_plot in the Environment pane containing the value NULL (empty). This is the return value of plot(); it returns nothing. Instead, it has an action (or more formally a side-effect) that prints the generated plot.

In the same way, the console output you see when you call str() is the function's side-effect since the return value is hidden. However, when you call lapply() with str(), you get the return value of calling str() on each element i.e. a list of NULLs.

P.S. It's not necessary that side-effect functions should return nothing. The return values of ggplot2 function calls for example are lists.

1 Like

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.