BaşlayınÜcretsiz Başlayın

Returning metadata

Sometimes you want to return multiple things from a function, but you want the result to have a particular class (for example, a data frame or a numeric vector), so returning a list isn't appropriate. This is common when you have a result plus metadata about the result. (Metadata is "data about the data". For example, it could be the file a dataset was loaded from, or the username of the person who created the variable, or the number of iterations for an algorithm to converge.)

In that case, you can store the metadata in attributes. Recall the syntax for assigning attributes is as follows.

attr(object, "attribute_name") <- attribute_value

Bu egzersiz

Introduction to Writing Functions in R

kursunun bir parçasıdır
Kursu Görüntüle

Egzersiz talimatları

  • Update pipeable_plot() so the result has an attribute named "formula" with the value of formula.
  • plt_dist_vs_speed, that you previously created, is shown. Examine its updated structure.

Uygulamalı interaktif egzersiz

Bu örnek kodu tamamlayarak bu egzersizi bitirin.

pipeable_plot <- function(data, formula) {
  plot(formula, data)
  # Add a "formula" attribute to data
  ___ <- ___
  invisible(data)
}

# From previous exercise
plt_dist_vs_speed <- cars %>% 
  pipeable_plot(dist ~ speed)

# Examine the structure of the result
___
Kodu Düzenle ve Çalıştır