unit Function in R (Example) | How to Create a Unit Object with the grid Package

 

In this R tutorial you’ll learn how to create a unit object using the unit() function of the grid package.

The content of the post looks as follows:

Let’s dig in.

Definition & Basic R Syntax of unit Function

 

Definition: The unit R function creates a data object with the class “unit”.

 

Basic R Syntax: Please find the basic R programming syntax of the unit function below.

unit(any_values, any_unit)                 # Basic R syntax of unit function

In the remaining tutorial, I’ll show an example for the application of the unit function in the R programming language.

 

Construction of Example Data

I’ll use the following data as basement for this R programming tutorial:

my_values <- 1:10                          # Create example data
my_values                                  # Print example data
# 1  2  3  4  5  6  7  8  9 10

As you can see based on the previous output of the RStudio console, our example data is a numeric vector containing of ten values.

The unit function is part of the grid package. We therefore also need to install and load the grid package:

install.packages("grid")                   # Install & load grid package in R
library("grid")

 

Example: Creating Unit Object Using unit() Function in R

The following R programming syntax explains how to convert a numeric vector to a data object having the unit class. Consider the following R code:

my_values_unit <- unit(my_values, "cm")    # Apply unit function
my_values_unit                             # Return converted data
# 1cm  2cm  3cm  4cm  5cm  6cm  7cm  8cm  9cm  10cm

As you can see based on the previous output of the RStudio console, we created a new data object called my_values_unit containing ten unit elements. For this example, we used the unit mm. However, you can basically use whatever unit of measurement you want.

Let’s also check the class of our new data object:

class(my_values_unit)                      # Check class of converted data
# "unit"

As you can see, our new data object has the unit class.

 

Video & Further Resources

I have recently published a video on my YouTube channel, which illustrates the R programming code of this article. You can find the video below:

 

 

In addition, you may have a look at the other articles of this website.

 

In summary: In this article, I explained how to apply the unit function in R. Please let me know in the comments below, in case you have any further questions.

 

Subscribe to the Statistics Globe Newsletter

Get regular updates on the latest tutorials, offers & news at Statistics Globe.
I hate spam & you may opt out anytime: Privacy Policy.


Leave a Reply

Your email address will not be published. Required fields are marked *

Fill out this field
Fill out this field
Please enter a valid email address.

Top