R Variables

Declaring Variables

In R, variables are created by assigning a value:

x <- 10
y = "R Language"

Both forms work, but <- is the standard style in R.

Naming Rules

Variable names:

  • Must start with a letter or . (dot)
  • Can include letters, numbers, dots, and underscores
  • Are case-sensitive
valid_name <- 100
.Valid <- "okay"
_invalid <- "not allowed"

Dynamic Typing

Variables can hold any type and change later:

Loading...
Output:

Reassigning Variables

You can reassign values at any point in a script:

temp <- 98.6
temp <- 37  # changes the value and type

Global vs Local Scope

x <- 5  # global

myFunc <- function() {
  x <- 10  # local
  print(x)
}

myFunc()
print(x)

The function prints 10, while the global x remains 5.

Best Practices

  • Use descriptive variable names (e.g., total_score instead of x)
  • Avoid overwriting functions like mean or sum
  • Prefer <- for consistency with R style guides

Need Help?

Ask the AI if you need help understanding or want to dive deeper in any topic