w3resource

R Programming: Concatenate two given Factors into 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 :

# Create the first factor 'f1' with random samples from LETTERS
f1 <- factor(sample(LETTERS, size=6, replace=TRUE))

# Create the second factor 'f2' with random samples from LETTERS
f2 <- factor(sample(LETTERS, size=6, replace=TRUE))

# Print a message indicating the start of the original factors
print("Original factors:")

# Print the first factor 'f1'
print(f1)

# Print the second factor 'f2'
print(f2)

# Concatenate the levels of both factors and create a new factor 'f'
f = factor(c(levels(f1)[f1], levels(f2)[f2]))

# Print a message indicating the result after concatenation
print("After concatenate factor becomes:")

# Print the concatenated factor 'f'
print(f)

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                         

Explanation:

  • Generate and Convert Factors:
    • Two factors, f1 and f2, are created by sampling 6 random letters from the LETTERS vector and converting these samples into factors.
  • Print Original Factors:
    • The code prints a message and then displays the original factors f1 and f2.
  • Concatenate Factors:
    • The levels of f1 and f2 are combined into a single vector. This vector is then converted into a new factor f.
  • Print Concatenated Factor:
    • A message is printed, followed by the display of the new factor f that results from concatenating the levels of f1 and f2.

    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?



Become a Patron!

Follow us on Facebook and Twitter for latest update.

It will be nice if you may share this link in any developer community or anywhere else, from where other developers may find this content. Thanks.

https://www.w3resource.com/r-programming-exercises/factors/r-programming-factors-exercise-4.php