Menu
Coddy logo textTech

Creating Vectors with c()

Part of the Fundamentals section of Coddy's R journey — lesson 56 of 78.

So far, you've worked with single values stored in variables. But what if you need to store multiple related values together, like a list of temperatures or a set of scores? This is where vectors come in.

A vector is R's fundamental data structure for storing multiple values of the same type. You create vectors using the c() function, where "c" stands for "combine":

temperatures <- c(72, 75, 68, 80, 77)
print(temperatures)

Output:

[1] 72 75 68 80 77

Vectors can hold any data type you've learned - numeric, character, or logical:

names <- c("Alice", "Bob", "Charlie")
passed <- c(TRUE, FALSE, TRUE)

print(names)
print(passed)

Output:

[1] "Alice"   "Bob"     "Charlie"
[1]  TRUE FALSE  TRUE

One important rule: all elements in a vector must be the same type. If you mix types, R will automatically convert them to a common type. You can check a vector's length using length():

scores <- c(85, 92, 78, 95)
print(length(scores))

Output:

[1] 4
challenge icon

Challenge

Easy

Create three vectors and print each one:

  1. A numeric vector called prices containing the values: 19.99, 29.99, 9.99, 49.99
  2. A character vector called colors containing: "red", "green", "blue"
  3. A logical vector called in_stock containing: TRUE, FALSE, TRUE, TRUE, FALSE

After creating all three vectors, print each vector followed by its length using the length() function.

Your output should be:

[1] 19.99 29.99  9.99 49.99
[1] 4
[1] "red"   "green" "blue" 
[1] 3
[1]  TRUE FALSE  TRUE  TRUE FALSE
[1] 5

Cheat sheet

A vector is R's fundamental data structure for storing multiple values of the same type.

Create vectors using the c() function (c stands for "combine"):

temperatures <- c(72, 75, 68, 80, 77)
names <- c("Alice", "Bob", "Charlie")
passed <- c(TRUE, FALSE, TRUE)

Vectors can hold numeric, character, or logical data types. All elements in a vector must be the same type.

Use length() to get the number of elements in a vector:

scores <- c(85, 92, 78, 95)
length(scores)  # Returns 4

Try it yourself

# TODO: Write your code below

# 1. Create a numeric vector called 'prices' with values: 19.99, 29.99, 9.99, 49.99


# 2. Create a character vector called 'colors' with values: "red", "green", "blue"


# 3. Create a logical vector called 'in_stock' with values: TRUE, FALSE, TRUE, TRUE, FALSE


# Print each vector followed by its length using length()
quiz iconTest yourself

This lesson includes a short quiz. Start the lesson to answer it and track your progress.

All lessons in Fundamentals