Developing R Packages from Scratch - GeeksforGeeks (2024)

Last Updated : 29 Aug, 2024

Comments

Improve

R is considered as a powerful language for statistical computing, machine learning and and data analysis. Its major strength lies in the way that it allows its users to develop their own packages. Creating an R package from scratch can seem as a hectic task, but with a structured approach, it becomes interesting to create and at the same time, it becomes more manageble. This guide helps to developing an R package, from setting up the project structure to sharing your package with the R community.

Why Develop an R Package?

The reasons of creating R package can be categorized into four categories such as –

  • Reuse: Package your functions and datasets for use across multiple projects.
  • Distribution: Share your code with colleagues or the broader R community.
  • Organization: Keep your code modular and well-organized.
  • Version Control: Track changes and maintain different versions of your package

Now we implement the steps involved in creating a R package,from Scratch in R Programming Language.

Step 1: Load Necessary Libraries and Dataset

First, ensure you have the devtools and roxygen packages installed and loaded.

R
install.packages("devtools")library("devtools")devtools::install_github("klutometis/roxygen")library(roxygen2)

Step 2: Create a New Package

  • Open RStudio.
  • Go to File > New Project > New Directory > R Package.
  • Enter the package name that you desire to give to your package.
  • Choose the directory on where the package is to be created.
  • Ensure that all the informations are correct , and then click create project.

After clicking the create project, you can now take a look at the final structure of your created package, including its components, which will look similar to the image given below.

Developing R Packages from Scratch - GeeksforGeeks (1)

Fig: Package Structure

  • DESCRIPTION: Metadata about your package (e.g., title, description, author, version, etc).
  • NAMESPACE: Controls which functions are exported from your package.
  • R/: Directory where your R scripts (functions) are stored.
  • man/: Directory for the documentation files, which will be automatically generated while creating the package.

Step 3: Write the Functions

  • In RStudio, navigate to the R/ directory within your package project that you have created. Right-click on the directory and select “New File” > “R Script”.
  • Begin coding your function in the newly created script. For example, let’s say you want to create a function named my_sum that calculates the sum of 2 numbers:
R
#' My First Function#'#' This function adds two numbers.#' #' @param x A numeric value.#' @param y A numeric value.#' @return The sum of x and y.#' @exportmy_function <- function(x, y) { return(x + y)}

Step 4: Document Your Functions

Documentation is important for any R package that is created as it ensures that users understand how to use your functions inside that package.Use the devtools package to generate the documentation and run the following command in the console.

devtools::document()

Output:

Developing R Packages from Scratch - GeeksforGeeks (2)

Fig: Description file of the package

  • The documentation files will be generated in the man/ directory of your package. Additionally, the NAMESPACE file will be updated to export the documented functions.
  • The DESCRIPTION file should also be updated to reflect the package’s metadata, including the title, description, version, author, and dependencies. You can also verify the changes by visiting the description file in the package structure.

Step 5: Add tests

First Install the required package to ensure that the functions work as expected.

R
install.package("testthat")

Next Create a tests/ directory in the package.Write test cases in scripts saved in the tests/testthat/ directory.


Now write the test code in the test script.

R
#test-your_function.R test_that("add_two_numbers works correctly", { # Define the inputs and expected outputs input1 <- 2 input2 <- 3 expected_output1 <- 5 # Test if the function returns the correct sum expect_equal(add_two_numbers(input1, input2), expected_output1) # Test if the function throws an error for incorrect input wrong_input <- "a" expect_error(add_two_numbers(wrong_input, input2))})

Output:

 devtools::test()
ℹ Testing Mypackage
Error in install.packages : Updating loaded packages
✔ | F W S OK | Context
✔ | 2 | your_function

══ Results ════════════════════════════════════════════
[ FAIL 0 | WARN 0 | SKIP 0 | PASS 2 ]

Step 6:Building and Checking the Package

Once your functions for the package and the documentation are in hand, it’s time to build and check the package for further usage and publications.

Build the Package

Use devtools::build() to create a .tar.gz file of your package, which can be shared or installed.

devtools::build()

Output:

devtools::build()
── R CMD build ────────────────────────────────────────
✔ checking for file 'C:\Users\srisa\OneDrive\Desktop\Rpackage\Mypackage/DESCRIPTION' (527ms)
─ preparing 'Mypackage': (604ms)
✔ checking DESCRIPTION meta-information ...
─ checking for LF line-endings in source and make files and shell scripts (537ms)
─ checking for empty or unneeded directories
Omitted 'LazyData' from DESCRIPTION
─ building 'Mypackage_0.1.0.tar.gz'

Check the Package

Run devtools::check() command to ensure there are no errors or warnings. This command checks the package for the common issues and verifies that everything is working correctly.

devtools::check()

Output:

0 error ✔ | 0 warnings ✔ | 0 notes ✔

Step 7:Sharing the Package

After you have created the package sucessfully, you can share them with the R dev community out there who are waiting for many new packages that would reduce their work in several ways such as:

  • Locally: Use install.packages(“path_to_your_package”) to install the package locally.
  • GitHub: Push your package to a GitHub repository and use devtools::install_github(“username/repository”) to install it.
  • CRAN: Submit your package to CRAN, the official R package repository, for wider distribution.

Conclusion

Developing an R package from scratch is a good practice that enhances your ability to organize, share, and reuse code. By following this article, you can create a well-documented, tested, and shareable R package. Whether you’re building tools for personal use or contributing to the R community, package development is an essential skill for any programmer who has R in his skill bucket.



tmpravi5i5j

Developing R Packages from Scratch - GeeksforGeeks (4)

Improve

Previous Article

Deploying a basic Streamlit app using Shiny package in R

Next Article

How to Choose Variable to Display in Tooltip When Using ggplotly in R

Please Login to comment...

Developing R Packages from Scratch - GeeksforGeeks (2024)

References

Top Articles
6 Amazing Edible Cookie Dough Recipes - Eggless Cookie Dough
How to Make Kettle Corn - CopyKat Recipes
Westfield Mall Kiosk Rental Prices
Min Player Speed Threshold Madden 22
Boldt Castle Webcam
Varsity Tutors, a Nerdy Company hiring Hoboken Vietnamese Tutor in Hoboken, NJ | LinkedIn
Bella 700 RAID - Powerboat and RIB
Cape Girardeau Mo Inmate Roster
Mywinners Wager Online
Yuliett Torres Lives
What Is The Value Of X 105O 115O 125O 135O
At 25 Years, Understanding The Longevity Of Craigslist
Scat Ladyboy
Moore Township Concerns
Ultimate Guide to Visiting Dungeness, UK
Nog Bible
Brimstone Sands Lost Easels
Bert Kish Longmire
Odawa Hypixel
Wat Prasri Chicago
Recruiting: Alabama trying to flip Michigan football's top 2025 commit
Driving Directions To The Closest Dollar Tree
Hillside Funeral Home Washington Nc Obituaries
R/Sandiego
Devotion Showtimes Near Xscape Theatres Blankenbaker 16
Centricity Kp Schedule
Directions To 401 East Chestnut Street Louisville Kentucky
Z-Ticket | An active card for summer in the Tiroler Zugspitz Arena
Paytexaswarrant
Truist Cash Reserve: Line of Credit | Truist
Telegram Scat
Uncover The Truth: Camilla Araujo Leaked Content Revealed
bitchinbubba face leak & bitchinbubba face reveal twitch| Discover
Eversource Outage Map Cape Cod
Hidden Figures Movie Quiz Answers
Pokemon Sapphire Evolution Chart
Elemental Showtimes Near Sedaliamovies
Skipthe Games.com
H0Tdommymommygf
2005 Chevrolet Silverado Radio Wiring Diagram
Csulb Atlas
Igumdrop Deepfake
Google Jobs Denver
What Is Z Drive in Windows 10 and How to Remove It Safely?
Vikram Vedha Download 2022
Cringe Valorant Matching Names
Tsc Boots Sale
Lake Wales Fl Craigslist
Mals Crazy Crab
Is Nadav In Rehab
In Control Lyrics Nba Youngboy
Latest Posts
Article information

Author: Twana Towne Ret

Last Updated:

Views: 5993

Rating: 4.3 / 5 (44 voted)

Reviews: 91% of readers found this page helpful

Author information

Name: Twana Towne Ret

Birthday: 1994-03-19

Address: Apt. 990 97439 Corwin Motorway, Port Eliseoburgh, NM 99144-2618

Phone: +5958753152963

Job: National Specialist

Hobby: Kayaking, Photography, Skydiving, Embroidery, Leather crafting, Orienteering, Cooking

Introduction: My name is Twana Towne Ret, I am a famous, talented, joyous, perfect, powerful, inquisitive, lovely person who loves writing and wants to share my knowledge and understanding with you.