0
0
R Programmingprogramming~5 mins

lapply and sapply in R Programming - Cheat Sheet & Quick Revision

Choose your learning style9 modes available
Recall & Review
beginner
What does the lapply() function do in R?

lapply() applies a function to each element of a list or vector and returns a list of the same length.

Click to reveal answer
beginner
How is sapply() different from lapply()?

sapply() tries to simplify the result of lapply(). It returns a vector or matrix if possible instead of a list.

Click to reveal answer
beginner
What type of output does lapply() always return?

lapply() always returns a list, no matter what the function returns for each element.

Click to reveal answer
beginner
If you want a simplified vector output instead of a list, which function should you use?

Use sapply() because it tries to simplify the output to a vector or matrix when possible.

Click to reveal answer
beginner
Example: What is the output of lapply(1:3, function(x) x^2)?

The output is a list: list(1, 4, 9) because lapply() returns a list of squared numbers.

Click to reveal answer
What does lapply() return when applied to a vector?
AA vector
BA list
CA matrix
DA data frame
Which function tries to simplify the output to a vector or matrix?
Asapply()
Btapply()
Capply()
Dlapply()
What will sapply(1:3, function(x) x^2) return?
Alist(1, 4, 9)
Bmatrix(1,4,9)
Cc(1, 4, 9)
Ddata frame
If the function applied returns different types or lengths, what does sapply() return?
AA list
BA simplified vector
CAn error
DA matrix
Which function is best when you want to keep the output as a list?
Asapply()
Btapply()
Capply()
Dlapply()
Explain the difference between lapply() and sapply() in R.
Think about the output type each function returns.
You got /4 concepts.
    When would you choose lapply() over sapply()?
    Consider the structure of the output you need.
    You got /3 concepts.