w3resource

R Programming: Change the first Level of a Factor

R Programming: Factors Exercise-2 with Solution

Write a R program to change the first level of a factor with another level of a given factor.

Sample Solution :

R Programming Code :

# Create a character vector with elements "a", "b", "a", "c", "b"
v = c("a", "b", "a", "c", "b")

# Print the original vector
print("Original vector:")
print(v)

# Convert the vector to a factor
f = factor(v)

# Print the factor of the vector
print("Factor of the said vector:")
print(f)

# Change the first level of the factor to "e"
levels(f)[1] = "e"

# Print the updated factor with the new level
print(f)

Output:

[1] "Original vector:"
[1] "a" "b" "a" "c" "b"
[1] "Factor of the said vector:"
[1] a b a c b
Levels: a b c
[1] e b e c b
Levels: e b c                         

Explanation:

  • v = c("a", "b", "a", "c", "b"): A character vector v is created with elements "a", "b", "a", "c", and "b".
  • print("Original vector:"): The message "Original vector:" is printed to the console.
  • print(v): The original vector v is printed, displaying its elements.
  • f = factor(v): The vector v is converted into a factor object f. Factors represent categorical data in R.
  • print("Factor of the said vector:"): The message "Factor of the said vector:" is printed to the console.
  • print(f): The factor f is printed, showing its levels and the values associated with each level.
  • levels(f)[1] = "e": The first level of the factor f (which is "a") is renamed to "e".
  • print(f): The updated factor f is printed, now showing the first level as "e" instead of "a".

R Programming Code Editor:



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

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

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-2.php