Merge two vectors in R programming
In this tutorial, we will learn how to merge two vectors in R programming.
TYPES
When we talk about merging the vectors, it can be done in 3 ways:
- Concatenation, which involves combining of vectors by appending them.
- Joining involves merging based on particular criteria.
- Binding, combing either row wise or column wise.
FUNCTIONS TO MERGE VECTORS in R
Case 1: c()
function, to combine vectors
n_v1 <- c(14,28,42) n_v2 <- c(56,70,84) concat_n <- c(n_v1,n_v2) concat_n
In the above code, we have created 2 vectors n_v1
and n_v2
, then used the concatenate function which appends both vectors.
Output:
[1] 14 28 42 56 70 84
Case 2: merge()
is certainly used to join vectors of similar columns.
n_v3 <- c(1, 2, 3) n_v4 <- c(4, 5, 6) x <- data.frame(ID = 1:3, val1 = n_v3) y <- data.frame(ID = 2:4, val2 = n_v4) mer_out <- merge(x,y, by = "ID") mer_out
In the above code once the two vectors or dataframes are created n_v3
and n_v4
merge function is used to join both vectors.
Output:
Case 3: rbind()
or cbind()
combines rows or columns.
n_v5 <- c(12,24, 36,48) n_v6 <- c(60,72) #row binding bindr <- rbind(n_v5,n_v6) bindr #column binding bindc <- cbind(n_v5,n_v6) bindc
In this code, vec1 and vec2 are merged row wise, using rbind()
and then column wise, using cbind()
function.
Output:
The above three functions show the different techniques of merging two vectors in R. As in the above examples we have similarly merged only 2 vectors we can add more vectors and continue in the same way. When dealing with a whole dataset, these different techniques are quite helpful in exploring data and taking smart moves at the right time.
Leave a Reply