How to combine two vectors in R ?
In this article, we will learn how to combine two vectors in R Programming Language. We can combine two or more vectors using function c() itself. While using function c() All arguments are coerced to a common type which is the type of the returned value.
Syntax: c(…)
Parameters:
- …: arguments to be combined
Returns: A vector
Steps –
- Create vectors to be combined
- Combine them using c()
- Display combined result
Example 1: Vectors of the same data type will give the vector of input data type as result.
R
a <- c (1, 2, 8) b <- c (5, 8, 9, 10) c <- c (a,b) c cat ( "typeof a" , typeof (a), " typeof b" , typeof (b), "typeof c" , typeof (c) , "\n" ) a <- c ( "geek" , "for" , "geek" ) b <- c ( "hello" , "coder" ) c <- c (a,b) c cat ( "typeof a" , typeof (a), " typeof b" , typeof (b), "typeof c" , typeof (c) , "\n" ) a <- c ( TRUE , FALSE , NA ) b <- c ( TRUE , FALSE ) c <- c (a,b) c cat ( "typeof a" , typeof (a), " typeof b" , typeof (b), "typeof c" , typeof (c) , "\n" ) |
Output:
[1] 1 2 8 5 8 9 10
typeof a double typeof b double typeof c double
[1] “geek” “for” “geek” “hello” “coder”
typeof a character typeof b character typeof c character
[1] TRUE FALSE NA TRUE FALSE
typeof a logical typeof b logical typeof c logical
While combining vectors of type double and character, character and logical, double and logical c() function return vector of a type character, character, double respectively.
Example 2:
R
a <- c (1, 2, 8) b <- c ( "hello" , "coder" ) c <- c (a,b) # a vector of type double and b vector of type # character result c vector of type character c cat ( "typeof a" , typeof (a), " typeof b" , typeof (b), "typeof c" , typeof (c) , "\n" ) a <- c ( "geek" , "for" , "geek" ) b <- c ( TRUE , FALSE ) # a vector of type character and b vector of type logical # result c vector of type character c <- c (a,b) c cat ( "typeof a" , typeof (a), " typeof b" , typeof (b), "typeof c" , typeof (c) , "\n" ) a <- c (1, 2, 8) b <- c ( TRUE , FALSE ) c <- c (a,b) # a vector of type double and b vector of type # logical result c vector of type double c cat ( "typeof a" , typeof (a), " typeof b" , typeof (b), "typeof c" , typeof (c) , "\n" ) |
Output:
[1] “1” “2” “8” “hello” “coder”
typeof a double typeof b character typeof c character
[1] “geek” “for” “geek” “TRUE” “FALSE”
typeof a character typeof b logical typeof c character
[1] 1 2 8 1 0
typeof a double typeof b logical typeof c double
Please Login to comment...