R Program to convert given pH levels of soil to an ordered factor

September 17, 2021, Learn eTutorial

How to convert given pH levels of soil to an ordered factor using the R program?

To convert a value to an ordered factor using the R program, we are using built-in functions levels(), and factor() for this conversion. The levels(), factor() functions in R compute the levels of factors of the vector in a single function.

Using the function factor() we can create a factor of the vector and by using the level() function we can find levels of a factor. Factors are stored as integer vectors and which is closely related to vectors. The syntax of these functions are 

levels(x) #where x is an object, for example, a factor
factor(x = character(), levels, labels = levels,exclude = NA, ordered = is.ordered(x), nmax = NA) 
#Where x is a vector of data, usually taking a small number of distinct values

In this R program, We are printing the original values to understand the values and then we directly give the values to built-in functions. And print the function result. Here we used variable PH for assigning ph values and variable PHF for finding the ordered factor value of the given ph values.


STEP 1: Assign variable PH with soil ph values

STEP 2: Display the original values

STEP 3:Call the built-in function factor with level as factor(PH, levels=c(3,7,10),ordered=TRUE)

STEP 4: Assign variable PHF with the function result

STEP 5: Print the ordered factor

R Source Code

                                          PH = c(1,3,10,7,5,4,3,7,8,7,5,3,10,10,7)
print("Original values of PH:")
PHF = factor(PH, levels=c(3,7,10),ordered=TRUE)
print("pH value to an ordered factor:")


[1] "Original values of PH:"
[1]  1  3 10  7  5  4  3  7  8  7  5  3 10 10  7
[1] "pH value to an ordered factor:"
[1]  3    10   7      3    7     7     3    10   10   7   
Levels: 3 < 7 < 10