Variables, Assignment & Basic Data Types

4.1 Assignment

Names: letters, digits, . and _; cannot start with a digit or underscore. Case-sensitive. Use snake_case. Non-syntactic names need backticks: ` my var <- 1 `.

x <- 5           # preferred assignment operator
y = 10           # also works (used for function arguments)
15 -> z          # right assignment (rare)
assign("w", 20)  # programmatic assignment
x <<- 1          # super-assignment to an enclosing environment (see §23)

4.2 Atomic types

3.14, 1e6, 5 "hello", 'a' TRUE, FALSE, NA

typeof(5)        # "double" — numbers are double by default
typeof(5L)       # "integer"
class(TRUE)      # "logical"
is.numeric(5); is.character("a"); is.logical(NA)
.Machine$integer.max     # 2147483647
.Machine$double.eps      # 2.220446e-16

4.3 Type conversion (coercion)

Implicit coercion hierarchy (when mixing types in a vector): logical < integer < double < complex < character

as.numeric("3.14")     # 3.14
as.integer(3.9)        # 3 (truncates)
as.character(42)       # "42"
as.logical("TRUE")     # TRUE
as.logical(0:2)        # FALSE TRUE TRUE
as.numeric("abc")      # NA with a warning
c(1, "a", TRUE)        # "1" "a" "TRUE"
c(1, TRUE, FALSE)      # 1 1 0
sum(c(TRUE, TRUE, FALSE))   # 2 — counting TRUEs is a common idiom

4.4 Printing & inspecting

print(x); x            # auto-print at the console
str(x)                 # compact structure — use it constantly
summary(x)
class(x); typeof(x); mode(x); length(x)
object.size(x)