AnyCompiler

Vectors and Assignment

R's conventional assignment operator is <-, not =. x <- 5 reads as "5, into x" and is the form you'll see in essentially all R code and documentation (= also works for assignment at the top level, but <- is the idiom). There's no declaration keyword of any kind — the first assignment to a name brings it into existence, the same minimal style Python and Ruby use.

c() (short for "combine") is how you build a vector of more than one element. Indexing is 1-based — x[1] is the first element, not the second — which is genuinely different from Python, JavaScript, Rust, Go, Java, C, C++, C#, Kotlin, and Swift, all of which start counting at 0.

x <- c(10, 20, 30)
print(x)
print(x[1])
print(length(x))
y <- 5
print(y[1])
print(length(y))
Output
[1] 10 20 30
[1] 10
[1] 3
[1] 5
[1] 1

x[1] correctly returns 10, the first element — not 20, which 0-based indexing would give you. But look at y: it was assigned a single number, 5, with no call to c() at all — and y[1] still works, returning 5, and length(y) reports 1. y was never "just a number" that indexing happens to tolerate; it was a numeric vector of length 1 from the moment it was created. Next: data types — numeric, character, logical, integer, and NA, plus what happens when a value can't be coerced into the type you asked for.

Practice exercise

Create x <- c(5, 10, 15) using <-, then print x[2] (remember R indexing starts at 1, not 0) and print length(x).