R Programming - Convert Soil pH Levels to ordered Factors
R Programming: Factors Exercise-5 with Solution
Write a R program to convert a given pH levels of soil to an ordered factor.
Note: Soil pH is a measure of the acidity or basicity of a soil. pH is defined as the negative logarithm of the activity of hydronium ions in a solution.
In soils, it is measured in a slurry of soil mixed with water, and normally falls between 3 and 10, with 7 being neutral.
Sample Solution :
R Programming Code :
# Create a vector with soil pH levels
ph = c(1,3,10,7,5,4,3,7,8,7,5,3,10,10,7)
# Print a message indicating that the following output is the original data
print("Original data:")
# Print the original vector of pH levels
print(ph)
# Convert the pH levels to an ordered factor with specified levels
ph_f = factor(ph, levels=c(3,7,10), ordered=TRUE)
# Print a message indicating that the following output is the ordered factor
print("pH levels of soil to an ordered factor:")
# Print the ordered factor version of the pH levels
print(ph_f)
Output:
[1] "Original data:" [1] 1 3 10 7 5 4 3 7 8 7 5 3 10 10 7 [1] "pH levels of soil to an ordered factor:" [1] <NA> 3 10 7 <NA> <NA> 3 7 <NA> 7 <NA> 3 10 10 7 Levels: 3 < 7 < 10
Explanation:
- Create a vector ph:
- ph = c(1,3,10,7,5,4,3,7,8,7,5,3,10,10,7)
- Defines a vector containing various pH levels of soil.
- Print original data:
- print("Original data:")
- Outputs a message indicating that the next output will display the original pH data.
- print(ph)
- Displays the vector of pH levels.
- Convert to an ordered factor:
- ph_f = factor(ph, levels=c(3,7,10), ordered=TRUE)
- Converts the ph vector into an ordered factor with specified levels (3, 7, and 10).
- ordered=TRUE ensures that the factor levels have a specific order (3 < 7 < 10).
- Print ordered factor:
- print("pH levels of soil to an ordered factor:")
- Outputs a message indicating that the next output will display the pH levels as an ordered factor.
- print(ph_f)
- Displays the pH levels as an ordered factor with the specified order of levels.
R Programming Code Editor:
Have another way to solve this solution? Contribute your code (and comments) through Disqus.
Previous: Write a R program to concatenate two given factor in a single factor.
Next: Write a R program to extract the five of the levels of factor created from a random sample from the LETTERS (Part of the base R distribution.)
Test your Programming skills with w3resource's quiz.
What is the difficulty level of this exercise?
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-5.php
- Weekly Trends and Language Statistics
- Weekly Trends and Language Statistics