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:
Syntax
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
numbers <- c(1, 2, 3)
combined <- c(numbers, 4, 5)
print(combined)
mixed <- c(1, 2, "three")
print(mixed)
cat(class(mixed), "\n")
Login to try C/C++/Java/PHP code in the editor
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
- Forgetting that
c(1, 2, "three")turns every element into a string, so1 + 1on it fails. - Using
c[1]when the function name isc, instead of storing the vector in a variable first. - 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: