R Program to concatenate two factors into a single factor

How to concatenate two given factors into a single factor

Here we are explaining how to write an R program to concatenate two given factors into a single factor. We can accomplish the concatenation using built-in functions such as levels() and factor(). In this case, the vector values are passed directly to these functions.

Using the function factor() we can create a factor of the vector and by using the level() function we find the levels of a factor. Factors are stored as integer vectors and are closely related to vectors.


levels(x) #where x is an object, for example, a factor
factor(x = character(), levels, labels = levels,exclude = NA, ordered = is.ordered(x), nmax = NA) 
#Where x is a vector of data, usually taking a small number of distinct values
 

How to concatenate two given factors in a single factor in the R Program

Below are the steps used in the R program to concatenate two given factors into a single factor. In this R program, we directly give the values to built-in functions. And print the function result. Here we used two variables namely fact1 and fact2 for assigning factor values. The third variable fact contains the concatenated factor and finally prints the resulting factor.

ALGORITHM

STEP 1: Assign variable fact1,fact2 with factor values

STEP 2: First print original factors values

STEP 3:Call the built-in function factor with level as factor(c(levels(fact1)[fact1], levels(fact2)[fact2]))

STEP 4: Assign variable fact with the function result

STEP 5: Print the concatenated factor

 

R Source Code

                                          fact1 <- factor(sample(LETTERS, size=6, replace=TRUE))
fact2 <- factor(sample(LETTERS, size=6, replace=TRUE))
print("Original factors are:")
print(fact1)
print(fact2)
fact= factor(c(levels(fact1)[fact1], levels(fact2)[fact2]))
print("After concatenate factor becomes:")
print(fact)
                                      

OUTPUT

[1] "Original factors are:"
[1] Q Y M J J H
Levels: H J M Q Y
[1] B J L S F Z
Levels: B F J L S Z
[1] "After concatenate factor becomes:"
[1] Q Y M J J H B J L S F Z
Levels: B F H J L M Q S Y Z