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:")
## [1] "Original factors are:"
print(fact1)
## [1] V J Q N E V
## Levels: E J N Q V
print(fact2)
## [1] B M E L Q D
## Levels: B D E L M Q
fact= factor(c(levels(fact1)[fact1], levels(fact2)[fact2]))

print("After concatenate factor becomes:")
## [1] "After concatenate factor becomes:"
print(fact)
##  [1] V J Q N E V B M E L Q D
## Levels: B D E J L M N Q V