w3resource

R Programming: Concatenate two given factor in a single factor

R Programming: Factors Exercise-4 with Solution

Write a R program to concatenate two given factor in a single factor.

Sample Solution :

R Programming Code :

f1 <- factor(sample(LETTERS, size=6, replace=TRUE))
f2 <- factor(sample(LETTERS, size=6, replace=TRUE))
print("Original factors:")
print(f1)
print(f2)
f = factor(c(levels(f1)[f1], levels(f2)[f2]))
print("After concatenate factor becomes:")
print(f)

Sample Output:

[1] "Original factors:"
[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                         

R Programming Code Editor:



Have another way to solve this solution? Contribute your code (and comments) through Disqus.

Previous: Write a R program to create an ordered factor from data consisting of the names of months.
Next: Write a R program to convert a given pH levels of soil to an ordered factor.

Test your Programming skills with w3resource's quiz.

What is the difficulty level of this exercise?



Follow us on Facebook and Twitter for latest update.