R Program to extract or replace parts of a factor

How to extract the five of the levels of factor created from a random sample from the LETTERS

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 

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

How to extract the levels of factor created from random samples in the R Program

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])


R Source Code

                                          Let = sample(LETTERS,size=50,replace=TRUE)
print("Original data:")
fac = factor(Let)
print("Original factors:")
print("Five of the levels")


[1] "Original data:"
 [1] "H" "N" "O" "D" "L" "E" "H" "U" "W" "W" "S" "Q" "A" "O" "I" "G" "G" "W" "T"
[20] "Z" "I" "S" "B" "P" "I" "F" "L" "B" "X" "A" "J" "V" "X" "C" "U" "A" "C" "W"
[39] "D" "J" "X" "C" "U" "O" "F" "V" "Y" "Z" "W" "Z"
[1] "Original factors:"
[1] H N O D L E H U W W S Q A O I G G W T Z I S B P I F L B X A J V X C U A C W
[39] D J X C U O F V Y Z W Z
Levels: A B C D E F G H I J L N O P Q S T U V W X Y Z
[1] "Five of the levels"

D H L N O 
1 1 1 1 1