Ad space (banner)
๐Ÿ“ŠR Lessons
Lesson 51 / 68

Type-agnostic general functions

This lesson covers writing type-agnostic functions in R, with the aim of producing flexible code that handles several types.

R is dynamically typed, so you write a general function that accepts a range of types simply by not specifying any. That flexibility is characteristic of R and handy when the same logic should serve numbers and strings alike.

In the sample code, larger() uses the concise if (a > b) a else b to compare both the numbers in larger(3, 7) and the strings in larger("apple", "banana"). The point is that > works on both.

A common early stumble is the absence of any explicit type check. Because R is dynamically typed you may not notice a problem until run time, and an unexpected type can produce an error.

In professional work, this flexibility is valued as an important way of raising reuse without writing near-identical methods per type.

๐Ÿ“– Reference code
โœ๏ธ Your code
Type your code, then press "Run"

๐Ÿงช This site can't compile or run R directly, so it checks on the spot whether what you typed matches the reference code (scoring happens entirely in your browser โ€” nothing is sent anywhere).

Ad space (banner)
Ad space (in-article)