how to interpret attributes in functions?

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

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

# Examine the structure of the result
str(plt_dist_vs_speed)

I don't know the goal of setting attr here.

I don't know the goal of setting attr here.

Then just leave it out and look at the difference.
Don't be afraid to try out some things!
You indicated in another post that you are following a tutorial.
You will learn most by just doing.

library(magrittr)

pipeable_plot <- function(data, formula) {
  plot(formula, data,main='function with return data')
  # Add a "formula" attribute to data
  attr(data, "formula") <- formula
  invisible(data)
}

pipeable_plot2 <- function(data, formula) {
  plot(formula, data,main='function with no return data')
  # Add a "formula" attribute to data
  # attr(data, "formula") <- formula
  # invisible(data)
}

# Note I added 'str' here
plt_dist_vs_speed <- cars %>% 
  pipeable_plot(dist ~ speed) %>%
  str()

#> 'data.frame':    50 obs. of  2 variables:
#>  $ speed: num  4 4 7 7 8 9 10 10 10 11 ...
#>  $ dist : num  2 10 4 22 16 10 18 26 34 17 ...
#>  - attr(*, "formula")=Class 'formula'  language dist ~ speed
#>   .. ..- attr(*, ".Environment")=<environment: 0x0000000012f74348>

plt_dist_vs_speed <- cars %>% 
  pipeable_plot2(dist ~ speed) %>%
  str()

#>  NULL

Created on 2020-08-01 by the reprex package (v0.3.0)

the purpose of setting attr there, is so that you could inspect the plt_dis_vs_speed object and see a formula associated with it.

This topic was automatically closed 21 days after the last reply. New replies are no longer allowed.