๐ŸŽ“ A1Learner
๐Ÿ”
0 of 33 lessons completed

R lapply

lapply() runs a function on every item in a list or vector. It always gives the results back as a list.

lapply over a list

mean runs on each item of the list. Each result prints under its list name.

scores <- list(a = c(10, 20), b = c(30, 40, 50))
print(lapply(scores, mean))

lapply over a vector

The input here is a plain vector. The result still prints as a list with numbered items.

print(lapply(c(1, 2, 3), function(x) x * 10))

lapply with a written function

add_ten is a function written for this job. lapply runs it on each item of nums.

add_ten <- function(x) {
  x + 10
}
nums <- list(first = c(1, 2), second = c(3, 4))
print(lapply(nums, add_ten))

Single results stay in a list

length gives one number for each item. The two numbers still print inside a list.

scores <- list(a = c(10, 20), b = c(30, 40, 50))
print(lapply(scores, length))

Example

teams <- list(red = c(5, 10), blue = c(20, 30))
totals <- lapply(teams, sum)
print(totals)
print(totals$red)

Key points

  • The first value in an lapply() call is the data.
  • The second value is the function to run on each item.
  • The result holds one item for each input item.
  • Names on the input list carry over to the result list.
  • The result is always a list, even when the input is a vector.
  • A function written for the job can be passed by its name.

In this example lapply adds up each team vector and returns the totals as a list. The last line picks the red total out of the list with $.

Try it Yourself

Edit the code, then press Run.

Running is simulated ยท rdrr.io R Snippets

Exercise

What does lapply() always return?