WalzoneInterview Prep
📞 Interviewing soon? Practice with a realistic AI mock phone interview — it calls you, then scores you. First 15 min FREE →

R · Intermediate · question 32 of 100

What are anonymous functions in R and how do you create one?

📕 Buy this interview preparation book: 100 R questions & answers — PDF + EPUB for $5

In R, an anonymous function is a function without a name. It’s a short, one-line function that is defined on the fly and used immediately without assigning it to a variable. Anonymous functions are also known as "lambda functions" or "function literals."

Here’s an example of how to create an anonymous function in R using the function() keyword:

    # Define an anonymous function to square a number
    squared <- function(x) x^2
    
    # Use the anonymous function to square the number 3
    result <- squared(3)
    
    # Print the result
    print(result)

In this example, we define an anonymous function using the function() keyword. The function takes one argument x and returns its square. We then call the function with the argument 3 and store the result in a variable called result, which we print to the console.

Anonymous functions are commonly used in R with functions like apply(), lapply(), and sapply(), where a short function needs to be passed as an argument. Here’s an example using sapply() to calculate the squares of a vector of numbers:

    # Create a vector of numbers
    numbers <- c(1, 2, 3, 4, 5)
    
    # Use sapply() and an anonymous function to square each number
    squared <- sapply(numbers, function(x) x^2)
    
    # Print the result
    print(squared)

In this example, we use sapply() to apply an anonymous function to each element of the numbers vector. The anonymous function takes one argument x and returns its square. The resulting vector squared contains the squares of each number in numbers.

In summary, anonymous functions are a convenient way to define short, one-line functions on the fly in R. They are useful for passing functions as arguments to other functions or for creating simple, reusable functions without defining them as separate objects.

Reading is step one. Saying it out loud is the interview. Our AI interviewer calls your phone and runs a realistic R interview — then scores it.
📞 Practice R — free 15 min
📕 Buy this interview preparation book: 100 R questions & answers — PDF + EPUB for $5

All 100 R questions · All topics