JosiahParry / youtube-tutorials

Code and slides used for youtube videos
https://josiahparry.github.io/youtube-tutorials/
12 stars 3 forks source link

s3 function methods #3

Open JosiahParry opened 1 year ago

JosiahParry commented 1 year ago

To understand s3 you need to understand some other things first

Objects in R Common Base R types
Atomic vectors On top of those are data.frames and matrix

Matrix are just vectors they get their special behavior from two things: first their class and then attributes

Let's look at attributes first. Attributes are essentially metadata for any R object.

View all attributes of objects with attributes() view a specific attribute with attr(x, "attr-name")

Set attributes with attr()

When we look at a matrix they have a dims attribute. This tells you how many columns and rows there are.

This, along with the "class" makes this vector a matrix with all the special behaviors of a matrix.

Now the difference between class and type is an important distinction. The ye TYPE always refers to the base R object type. Whereas the class can be any attribution on top of those.

So a matrix is a vector type with an attribute and a class. An object can have multiple classes. There is often a base class (the basic R type) and then a "sub class" on top of that

One thing to note while we're on the topic of matrix is that since they're just a single vector with special attributes that means they have all the same limitations as a normal vector. That means it can only hold the same amount of data as a vector

Now, let's avert our attention to the data.frame. It's type is a list.

It has attributes row names and col names

It also has

NOTE HELPER FUNCTION unclass() to see what an object really is

JosiahParry commented 1 year ago

S3 methods can be extended by other people! You cannot modify non-s3 functions to work with your custom objects. You would need a wrapper function. With s3 you allow your code to be extensible.