
Problem –
You want to create a Vector in R.
Solution –
To create a vector in R, we use the c(…) operator. A vector can contains either numbers, strings or logical values but not mixture.
Let’s see how to create a vector in R.
> a <- c(5, 10, 15, 20, 25)
> b <- c("R","is","awesome")
> c <- c(TRUE, FALSE, FALSE, TRUE)
If the arguments to c(…) are themselves vectors, it flattens them and combines them into one single vector.
> v1 <- c(1, 2, 3)
> v2 <- c(4, 5, 6)
> v3 <- c(v1, v2)
> v3
[1] 1 2 3 4 5 6
Vectors can not contains a mix of data types, such as numbers and strings. If you create a vector from mixed elements R will try to accommodate you by converting one of them.
> v1 <- c(1, 2, 3)
> v2 <- c("A","B","c")
> v3 <- c(v1, v2)
> v3
[1] "1" "2" "3" "A" "B" "c"
Here we tried to create a vector with numbers and string, so R converted all of the numbers to strings before creating the vector.