How to Create Vector in R: Simple Syntax and Examples
In R, you create a vector using the
c() function by combining values inside parentheses separated by commas. For example, c(1, 2, 3) creates a numeric vector with three elements.Syntax
The basic syntax to create a vector in R is using the c() function, which stands for 'combine'. Inside the parentheses, you list the elements separated by commas.
- c(): Function to combine elements into a vector.
- Elements: Values of the same or different types (numbers, characters, logicals).
r
vector_name <- c(element1, element2, element3, ...)
Example
This example shows how to create a numeric vector and a character vector using c(). It also prints the vectors to show their contents.
r
numbers <- c(10, 20, 30, 40) print(numbers) words <- c("apple", "banana", "cherry") print(words)
Output
[1] 10 20 30 40
[1] "apple" "banana" "cherry"
Common Pitfalls
One common mistake is mixing different data types in a vector, which causes R to convert all elements to a single type, usually character. Another is forgetting to use c() and trying to assign multiple values directly, which causes an error.
r
# Wrong: assigning multiple values without c() # numbers <- 1, 2, 3 # This will cause an error # Right: use c() to combine values numbers <- c(1, 2, 3) print(numbers) # Mixing types example mixed <- c(1, "two", TRUE) print(mixed) # All elements become characters
Output
[1] 1 2 3
[1] "1" "two" "TRUE"
Quick Reference
| Function | Description | Example |
|---|---|---|
| c() | Combine elements into a vector | c(1, 2, 3) |
| print() | Display vector contents | print(c("a", "b")) |
| typeof() | Check vector element type | typeof(c(1, 2)) |
| length() | Get number of elements | length(c(1, 2, 3)) |
Key Takeaways
Use the c() function to create vectors by combining elements.
All elements in a vector must be of the same type; mixing types converts them to a common type.
Always separate elements with commas inside c().
Use print() to see the contents of a vector.
Avoid assigning multiple values without c(), as it causes errors.