R Program to concatenate two factors into a single factor


February 25, 2023, Learn eTutorial
1657

What is Concatenation?

Concatenation is joining two or more values (numbers, characters, or strings) together, (like the second value will be added to the end of the first value) to form a single value. For example, suppose we have two strings "learn" and "programming". now we are concatenating the two strings to form a single string " learn programming"

How to concatenate two given factors using the R program?

We can accomplish the concatenation in R programming using built-in functions such as levels() and factor().

  • the function factor() we can create a factor of the vector
  • the function level() we can find the levels.

Finally, they are stored as integers and are closely related to vectors.


levels(x)

  • where x is an object,

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

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 value and finally prints the results.

ALGORITHM

STEP 1: Assign variable fact1, fact2 

STEP 2: First print the original 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 result value

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:")
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:"
[1] Q Y M J J H B J L S F Z
Levels: B F H J L M Q S Y Z