How to Use c() Function in R: Simple Guide with Examples
In R, the
c() function combines multiple values into a single vector. You can pass numbers, strings, or logical values inside c() to create a vector that holds them all together.Syntax
The c() function takes one or more values separated by commas and returns a vector containing all those values.
- c(...): Combines values into a vector.
...: Values can be numbers, strings, or logicals.
r
c(value1, value2, value3, ...)
Example
This example shows how to combine numbers and strings into vectors using c(). It demonstrates creating numeric and character vectors.
r
numbers <- c(1, 2, 3, 4, 5) print(numbers) words <- c("apple", "banana", "cherry") print(words)
Output
[1] 1 2 3 4 5
[1] "apple" "banana" "cherry"
Common Pitfalls
One common mistake is mixing different types without realizing R will convert them all to a single type. For example, mixing numbers and strings will convert numbers to strings.
Also, forgetting commas between values causes errors.
r
mixed <- c(1, "two", 3) print(mixed) # Numbers become strings # Wrong: c(1 "two" 3) # Missing commas cause error
Output
[1] "1" "two" "3"
Quick Reference
| Usage | Description |
|---|---|
| c(1, 2, 3) | Creates a numeric vector with values 1, 2, and 3 |
| c("a", "b", "c") | Creates a character vector with strings a, b, and c |
| c(TRUE, FALSE, TRUE) | Creates a logical vector with TRUE and FALSE values |
| c(1, "a") | Combines numeric and character; all become character |
Key Takeaways
Use
c() to combine values into a vector in R.All values inside
c() become the same type, so mixing types converts them.Separate values with commas inside
c() to avoid syntax errors.You can combine numbers, strings, and logical values with
c().Remember
c() always returns a vector, which is a basic data structure in R.