← Back to R Course | Chapter 3: Vectors | Lesson 1 of 7

Creating Vectors

A vector is a line of values of the same kind stored together, like a row of same-colored beads on a string. It is the most basic container in R.

In this page:

  1. Creating Vectors
Syntax
r
vector_name <- c(value1, value2, value3)
vector_name <- 1:10
vector_name <- seq(from, to, by = step)

Creating Vectors

A vector is R's most fundamental data structure -- an ordered collection of values that all share the same type. Even a single value like x <- 5 is technically a vector of length 1.

Vectors are the building block that most of R's other data structures, like matrices and data frames, are built from.

Note: Almost everything in R is a vector, even scalars -- there is no separate single-value type.

Example: Creating Vectors

markup
x <- 5
y <- c(1, 2, 3, 4, 5)

cat(length(x), length(y), "\n")
print(y)
Related Topics
{# common_mistakes/chapter_summary/browser_support: on Hindi pages the view already swaps in the hi_ translation fields (or blanks these out if untranslated), so this renders correctly for both languages without a lang_code check here. #}
Common Mistakes
  1. Writing y <- (1, 2, 3) without c, which is a syntax error.
  2. Expecting a single value like x <- 5 to be different from a vector, when in R it is a vector of length 1.
  3. Mixing types such as c(1, "a") and being surprised that all elements become characters.
🔒

Chapter Quiz — Complete all 7 topics to unlock

0/7 topics done

Complete these topics first:

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.