Base R defines an identity
function, a trivial identity function returning its argument (quoting from ?identity
).
It is defined as :
identity <- function (x){x}
Why would such a trivial function ever be useful? Why would it be included in base R?
I use it from time to time with the apply function of commands.
For instance, you could write
t()
as:Here is usage example:
here we are grouping ints into a int/count map. Collectors.groupingBy accepts a Function. In our case we need a function which returns the argument. Note that we could use
e->e
lambda insteadI just used it like this:
Stepping away from functional programming,
identity
is also used in another context in R, namely statistics. Here, it is used to refer to the identity link function in generalized linear models. For more details about this, see?family
or?glm
. Here is an example:However, in this case parsing it as a string instead of a function will achieve the same:
glm(y ~x, family=quasi(link="identity"))
EDIT: As noted in the comments below, the function
base::identity
is not what is used by the link constructor, and it is just used for parsing the link name. (Rather than deleting this answer, I'll leave it to help clarify the difference between the two.)Don't know about R, but in a functional language one often passes functions as arguments to other functions. In such cases, the constant function (which returns the same value for any argument) and the identity function play a similar role as 0 and 1 in multiplication, so to speak.
For whatever it's worth, it is located in
funprog.R
(the functional programming stuff) in the source of the base package, and it was added as a "convenience function" in 2008: I can imagine (but can't give an immediate example!) that there would be some contexts in the functional programming approach (i.e. usingFilter
,Reduce
,Map
etc.) where it would be convenient to have an identity function ...