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.
– Where x is a vector of data, usually taking a small number of distinct values
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.
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