R Vectors

R Vectors

A vector is the most fundamental, simplest data structure available in R.

It is a sequence of data elements that strictly share the exact same basic data type.


Creating a Vector

To create a vector, you use the highly versatile c() function.

The c stands for "combine" or "concatenate".

You simply pass your comma-separated values directly into the function!

Creating Vectors Example:

# A vector of numeric values
numbers <- c(10, 20, 30, 40)
# A vector of character strings
fruits <- c("Apple", "Banana", "Cherry")

print(numbers) print(fruits)


The Strict Type Rule

A vector cannot hold both numbers and strings simultaneously.

If you attempt to mix data types, R will automatically convert them all to the same type!

This automatic conversion is called "coercion", and it usually turns everything into character strings.


Accessing Vector Elements

You can easily access specific items in a vector by using square brackets [].

Unlike many other programming languages, R vectors are strictly 1-indexed.

This means the very first element is accessed using [1], not [0]!


Exercise 1 of 2

?

Which built-in function is used to securely create a vector in R?

Exercise 2 of 2

?

What happens if you attempt to create a vector containing both numbers and strings?