Creating a New Package
Now that we know why packages are useful, let’s walk through creating one.
The goal here is to use the {usethis}
package to handle all the setup steps — no manual file editing, no guesswork.
Step 1: Create the Package Folder
Use usethis::create_package()
to scaffold your project:
::create_package("path/to/mypackage") usethis
This will:
- Create a new folder called
mypackage
- Add essential files (
DESCRIPTION
,NAMESPACE
, etc.) - Open the new project in RStudio
Best practice: Use a folder name that matches your intended package name exactly.
What’s Inside the New Package?
When you run create_package()
, you’ll get this structure:
mypackage/
├── DESCRIPTION
├── NAMESPACE
├── R/
└── mypackage.Rproj
File/folder | Purpose |
---|---|
DESCRIPTION |
Metadata about your package |
NAMESPACE |
Tracks exports and imports |
R/ |
Place all your functions here |
.Rproj |
Makes it a project in RStudio |
Step 2: Use Git (Highly Recommended)
Even if you’re working alone, Git makes it easy to:
- Track changes over time
- Sync with GitHub or GitLab
- Undo mistakes
Set up Git:
::use_git() usethis
This:
- Initializes a local Git repo
- Adds a
.gitignore
file - Makes a first commit
You can link your package to GitHub later with:
::use_github() usethis
⚠️ A Note About Data and Git
Before committing anything to Git — especially data — pause and double-check:
- Is this data sensitive, internal, or private?
- Are you legally or contractually allowed to store or share it?
- Would it be safe in a public repo someday?
Even private GitHub repos are not fully secure. Assume anything committed could eventually be seen.
Ignore raw or sensitive data
Update your .gitignore
to prevent accidental leaks:
# .gitignore
data-raw/
*.csv
*.xlsx
*.rds
For extra protection, keep data in external storage or use .Rbuildignore
to exclude it from the built package.
Step 3: Open in a Clean Session
Once your package is created:
- Close other open RStudio projects
- Reopen the
.Rproj
file - Run:
::load_all() devtools
You’re now developing a package!
FAQ
Can I use spaces or dashes in the package name?
🚫 No. Package names must:
- Start with a letter
- Contain only letters, numbers, or periods (
.
) - Be lowercase
- Not already exist on CRAN (if publishing)
Where should I save my package?
Anywhere! But ideally:
- In a version-controlled folder (e.g. within a
~/code
or~/projects
) - Not inside another R project (to avoid nesting issues)
Do I need to understand everything inside DESCRIPTION
and NAMESPACE
?
Not yet! We’ll dive into those next. For now, trust {usethis}
and {roxygen2}
to handle them.
What’s Next?
Now that the scaffolding is in place, let’s write your first function and start building your package’s logic.