Here we are explaining how to write an R program to extract the five of the levels of factor created from a random sample from the LETTERS. Here we are using a built-in function factor() for this conversion. The vector values are passed to these functions directly here. The factor() functions in R computes the factors of the vector in a single function.
Using the function factor() we can create a factor of the vector. 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 extract the levels of factors created from random samples. In this R program, we directly give the values to built-in functions. And print the function result. Here we used variable Let for holding sample data and variable fac for finding the factors of the given data. Print the resulting factors.
STEP 1: Assign variable Let with sample data STEP 2: First print original data values STEP 3:Call the built-in function factor as fac = factor(Let) STEP 4: Assign variable fac with the function result STEP 5: Find the 5 levels as Let[1:5] STEP 6: Give a table view for the result factors as table(Let[1:5])
Let = sample(LETTERS,size=50,replace=TRUE)
print("Original data:")
## [1] "Original data:"
print(Let)
## [1] "S" "H" "T" "W" "R" "N" "J" "J" "S" "A" "L" "T" "J" "U" "T" "H" "W" "C" "Q"
## [20] "V" "B" "P" "F" "W" "R" "E" "R" "G" "T" "Z" "D" "X" "Z" "J" "Y" "B" "U" "H"
## [39] "V" "E" "P" "W" "X" "C" "E" "W" "A" "O" "C" "N"
fac = factor(Let)
print("Original factors:")
## [1] "Original factors:"
print(fac)
## [1] S H T W R N J J S A L T J U T H W C Q V B P F W R E R G T Z D X Z J Y B U H
## [39] V E P W X C E W A O C N
## Levels: A B C D E F G H J L N O P Q R S T U V W X Y Z
print("Five of the levels")
## [1] "Five of the levels"
print(Let[1:5])
## [1] "S" "H" "T" "W" "R"
print(table(Let[1:5]))
##
## H R S T W
## 1 1 1 1 1