Here we are explaining how to write an R program to convert given pH levels of soil to an ordered factor. Here we are using built-in functions levels(),factor() for this conversion. The vector values are passed to these functions directly here. The levels(), factor() functions in R computes 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
– Where x is a vector of data, usually taking a small number of distinct values
Below are the steps used in the R program to convert given pH levels of soil to an ordered factor. In this R program, 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.
PH = c(1,3,10,7,5,4,3,7,8,7,5,3,10,10,7)
print("Original data:")
## [1] "Original data:"
print(PH)
## [1] 1 3 10 7 5 4 3 7 8 7 5 3 10 10 7
PHF = factor(PH,levels=c(3,7,10), ordered=TRUE)
print("pH levels of soil to an ordered factor:")
## [1] "pH levels of soil to an ordered factor:"
print(PHF)
## [1] <NA> 3 10 7 <NA> <NA> 3 7 <NA> 7 <NA> 3 10 10 7
## Levels: 3 < 7 < 10