2. Variables - JulTob/R GitHub Wiki

🗺️ Map of Variables and Workspace

“Every chest needs a key, and every key needs a name, and every name marks a place on the map!”

In R, variables are simply names that point to objects: numbers, strings, vectors, charts, you name it. Once created, they live in the workspace, waitin’ for your command.

⚓ Creating Variables

> a <- 2
> b <- 3
> a
[1] 2

Use <- to assign a value to a name. The name becomes a variable and stores an object.

Ye can use = too, but <- be the traditional cutlass of R sailors.

🔍 Check the Workspace

Your workspace is like your deck: it holds all variables you’ve created.

> objects()
[1] "a" "b"

To search for names matchin’ a pattern:

> objects(pattern = "a")
[1] "a"

This is useful when your workspace gets cluttered with cargo.

🗑️ Remove Variables

To toss unwanted cargo overboard:

> rm(b)
> objects()
[1] "a"

Ye can also scuttle the whole deck with:

> rm(list = objects())

This clears everything! Be warned!

✏️ Editing Variables or Functions

Want to edit an object manually? R offers some clunky but possible tools:

> fix(a)

Or:

> edit(a)

⚠️ These open the object in a basic editor, often not great for structured types. Works best with functions or simple values.

Pro tip: Prefer editing your script directly in RStudio rather than using fix()—it’s like patchin’ a sail blindfolded.

🪝 A Word on Objects

In R, everything is an object (kind of): numbers, functions, even models and plots. When ye create a variable, you’re naming the object so you can reuse it later.

> typeof(a)
[1] "double"

> is.object(a)
[1] FALSE  # This checks for *S3* objects—don't fret yet!

Workspace

You can check all the variables in your workspace by Listing them:

ls()