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

The c() Function

The c function, short for combine, glues single values or shorter lists together into a longer vector. It is like clipping beads onto a chain.

In this page:

  1. The c() Function
Syntax
r
combined <- c(value1, value2, value3)
longer <- c(vector1, vector2)

The c() Function

c() (combine) builds a vector out of individual values or merges existing vectors together.

If the values have mixed types, R coerces them all to the most general common type, such as converting numbers to strings if any element is a character. This coercion rule is important to keep in mind when combining data from different sources.

Warning: c(1, 2, "three") coerces every element to character -- mixing types silently promotes the whole vector to the most general type.

Example: The c() Function

markup
numbers <- c(1, 2, 3)
combined <- c(numbers, 4, 5)
print(combined)

mixed <- c(1, 2, "three")
print(mixed)
cat(class(mixed), "\n")
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. Forgetting that c(1, 2, "three") turns every element into a string, so 1 + 1 on it fails.
  2. Using c[1] when the function name is c, instead of storing the vector in a variable first.
  3. Naming a variable c, which hides nothing but makes code confusing, when functions and variables can share the name.
🔒

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.