MulaiMulai sekarang secara gratis

sapply with functions that return NULL

You already have some apply tricks under your sleeve, but you're surely hungry for some more, aren't you? In this exercise, you'll see how sapply() reacts when it is used to apply a function that returns NULL over a vector or a list.

A function print_info(), that takes a vector and prints the average of this vector, has already been created for you. It uses the cat() function.

Latihan ini adalah bagian dari kursus

Intermediate R

Lihat Kursus

Petunjuk latihan

  • Apply print_info() over the contents of temp with sapply().
  • Repeat this process with lapply(). Do you notice the difference?

Latihan interaktif praktis

Cobalah latihan ini dengan menyelesaikan kode contoh berikut.

# temp is already available in the workspace

# Definition of print_info()
print_info <- function(x) {
  cat("The average temperature is", mean(x), "\n")
}

# Apply print_info() over temp using sapply()


# Apply print_info() over temp using lapply()
Edit dan Jalankan Kode