SlideShare uma empresa Scribd logo
1 de 17
FACTORS
Factors are the data objects which are used to
categorize the data and store it as levels.
They can store both strings and integers.
They are useful in the columns which have a
limited number of unique values.
Like "Male, "Female" and True, False etc. They are
useful in data analysis for statistical modeling.
Factors are created using the factor () function by
taking a vector as input.
• data <-
c("East","West","East","North","North","East",
"West","West","West","East","North")
• print(data) print(is.factor(data))
• # Apply the factor function.
• factor_data <- factor(data)
• print(factor_data)
• print(is.factor(factor_data))
Factors in Data Frame
• On creating any data frame with a column of text data, R
treats the text column as categorical data and creates factors
on it.
• height <- c(132,151,162,139,166,147,122)
• weight <- c(48,49,66,53,67,52,40)
• gender <-
c("male","male","female","female","male","female","male")
• # Create the data frame.
• input_data <- data.frame(height,weight,gender)
print(input_data)
• # Test if the gender column is a factor.
print(is.factor(input_data$gender))
• # Print the gender column so see the levels.
print(input_data$gender)
Changing the Order of Levels
• The order of the levels in a factor can be changed
by applying the factor function again with new
order of the levels.
• data <-
c("East","West","East","North","North","East","W
est", "West","West","East","North")
• factor_data <- f
• new_order_data <- factor(factor_data,levels =
c("East","West","North"))
print(new_order_data)actor(data)
print(factor_data)
Generating Factor Levels
• We can generate factor levels by using the gl() function.
• It takes two integers as input which indicates how many levels and
how many times
• Syntax
• gl(n, k, labels) Following is the description of the parameters used −
• n is a integer giving the number of levels.
• k is a integer giving the number of replications.
• labels is a vector of labels for the resulting factor levels.
• each level
• Example
• v <- gl(3, 4, labels = c("Tampa", "Seattle","Boston"))
• print(v)
Checking for a Factor in R
• The function is.factor() is used to check whether the variable
is a factor and returns “TRUE” if it is a factor.
• gender <- factor(c("female", "male", "male", "female"));
• print(is.factor(gender))
• Accessing elements of a Factor in R
• Like we access elements of a vector, the same way we access
the elements of a factor. If gender is a factor then gender[i]
would mean accessing ith element in the factor.
• Example:
• gender <- factor(c("female", "male", "male", "female"));
• gender[3]
• gender <- factor(c("female", "male", "male", "female"));
• gender[c(2, 4)]
•
Modification of a Factor in R
• After a factor is formed, its components can be modified but the
new values which need to be assigned must be at the predefined
level.
• Example:
• gender <- factor(c("female", "male", "male", "female" ));
• gender[2]<-"female"
• gender
• ender <- factor(c("female", "male", "male", "female" ));
•
• # add new level
• levels(gender) <- c(levels(gender), "other")
• gender[3] <- "other"
• gender
Factors in Data Frame
• The Data frame is similar to a 2D array with the columns
containing all the values of one variable and the rows
having one set of values from every column. There are
four things to remember about data frames:
• column names are compulsory and cannot be empty.
• Unique names should be assigned to each row.
• The data frame’s data can be only of three types- factor,
numeric, and character type.
• The same number of data items must be present in each
column.
• In R language when we create a data frame, its column is
categorical data and hence a factor is automatically
created on it.
We can create a data frame and check if its column is a
factor.
• Example:
• age <- c(40, 49, 48, 40, 67, 52, 53)
• salary <- c(103200, 106200, 150200,
• 10606, 10390, 14070, 10220)
• gender <- c("male", "male", "transgender",
• "female", "male", "female",
"transgender")
• employee<- data.frame(age, salary, gender)
• print(employee)
• print(is.factor(employee$gender))
• Gender<-
sample(c("Male","Female"),20,replace=TRUE)
• Values<-rnorm(20,mean=0,sd=1)
• Group<-sample(letters[1:5],20,replace=TRUE)
•
• df<-data.frame(Gender,Values,Group)
• library(ggplot2)
•
• # creating a boxplot
• ggplot(df,aes(Gender,Values))+geom_boxplot(aes
(fill=Group))
LIST
• Lists are the R objects which contain elements of different
types like − numbers, strings, vectors and another list
inside it.
• A list can also contain a matrix or a function as its
elements.
• List is created using list() function.
• Creating a List
• Following is an example to create a list containing strings,
numbers, vectors and a logical values.
• # Create a list containing strings, numbers, vectors and a
logical # values.
• list_data <- list("Red", "Green", c(21,32,11), TRUE, 51.23,
119.1)
• print(list_data)
Naming List Elements
• The list elements can be given names and they can be
accessed using these names.
• # Create a list containing a vector, a matrix and a list.
• list_data <- list(c("Jan","Feb","Mar"), matrix(c(3,9,5,1,-
2,8), nrow = 2), list("green",12.3))
• # Give names to the elements in the list.
names(list_data) <- c("1st Quarter", "A_Matrix", "A Inner
list")
• # Show the list.
• print(list_data)
Accessing List Elements
• Elements of the list can be accessed by the index of the element in
the list. In case of named lists it can also be accessed using the
names.
• We continue to use the list in the above example −
• # Create a list containing a vector, a matrix and a list.
• list_data <- list(c("Jan","Feb","Mar"), matrix(c(3,9,5,1,-2,8), nrow =
2), list("green",12.3))
• # Give names to the elements in the list.
• names(list_data) <- c("1st Quarter", "A_Matrix", "A Inner list")
• # Access the first element of the list.
• print(list_data[1])
• # Access the thrid element.
• As it is also a list, all its elements will be printed.
• print(list_data[3])
• # Access the list element using the name of the element.
print(list_data$A_Matrix)
Manipulating List Elements
• We can add, delete and update list elements as shown below. We can
add and delete elements only at the end of a list. But we can update
any element.
• # Create a list containing a vector, a matrix and a list.
• list_data <- list(c("Jan","Feb","Mar"), matrix(c(3,9,5,1,-2,8), nrow = 2),
list("green",12.3))
• # Give names to the elements in the list. names(list_data) <- c("1st
Quarter", "A_Matrix", "A Inner list")
• # Add element at the end of the list.
• list_data[4] <- "New element" print(list_data[4])
• # Remove the last element.
• list_data[4] <- NULL
• # Print the 4th Element.
• print(list_data[4])
• # Update the 3rd Element.
• list_data[3] <- "updated element"
• print(list_data[3])
Merging Lists
• You can merge many lists into one list by
placing all the lists inside one list() function
• # Create two lists. list1 <- list(1,2,3) list2 <-
list("Sun","Mon","Tue") # Merge the two lists.
merged.list <- c(list1,list2) # Print the merged
list. print(merged.list)
Converting List to Vector
• A list can be converted to a vector so that the
elements of the vector can be used for further
manipulation. All the arithmetic operations on
vectors can be applied after the list is
converted into vectors. To do this conversion,
we use the unlist() function. It takes the list as
input and produces a vector.
• # Create lists.
• list1 <- list(1:5)
• print(list1)
• list2 <-list(10:14)
• print(list2)
• # Convert the lists to vectors.
• v1 <- unlist(list1)
• v2 <- unlist(list2)
• print(v1)
• print(v2)
• # Now add the vectors
• result <- v1+v2
• print(result)

Mais conteúdo relacionado

Mais procurados

Mais procurados (20)

R Basics
R BasicsR Basics
R Basics
 
Data frame operations
Data frame operationsData frame operations
Data frame operations
 
2. R-basics, Vectors, Arrays, Matrices, Factors
2. R-basics, Vectors, Arrays, Matrices, Factors2. R-basics, Vectors, Arrays, Matrices, Factors
2. R-basics, Vectors, Arrays, Matrices, Factors
 
Linear Regression.pptx
Linear Regression.pptxLinear Regression.pptx
Linear Regression.pptx
 
Data Analysis with Python Pandas
Data Analysis with Python PandasData Analysis with Python Pandas
Data Analysis with Python Pandas
 
SQL Functions
SQL FunctionsSQL Functions
SQL Functions
 
Chart and graphs in R programming language
Chart and graphs in R programming language Chart and graphs in R programming language
Chart and graphs in R programming language
 
Python Collections
Python CollectionsPython Collections
Python Collections
 
Data manipulation on r
Data manipulation on rData manipulation on r
Data manipulation on r
 
SQL BUILT-IN FUNCTION
SQL BUILT-IN FUNCTIONSQL BUILT-IN FUNCTION
SQL BUILT-IN FUNCTION
 
Data manipulation with dplyr
Data manipulation with dplyrData manipulation with dplyr
Data manipulation with dplyr
 
R programming Fundamentals
R programming  FundamentalsR programming  Fundamentals
R programming Fundamentals
 
Data Management in R
Data Management in RData Management in R
Data Management in R
 
Data analytics with R
Data analytics with RData analytics with R
Data analytics with R
 
Single row functions
Single row functionsSingle row functions
Single row functions
 
Data Visualization With R
Data Visualization With RData Visualization With R
Data Visualization With R
 
R Programming: Introduction to Matrices
R Programming: Introduction to MatricesR Programming: Introduction to Matrices
R Programming: Introduction to Matrices
 
Pandas
PandasPandas
Pandas
 
dplyr Package in R
dplyr Package in Rdplyr Package in R
dplyr Package in R
 
ARIMA.pptx
ARIMA.pptxARIMA.pptx
ARIMA.pptx
 

Semelhante a Factors.pptx

Data Analysis and Programming in R
Data Analysis and Programming in RData Analysis and Programming in R
Data Analysis and Programming in R
Eshwar Sai
 

Semelhante a Factors.pptx (20)

R교육1
R교육1R교육1
R교육1
 
R training3
R training3R training3
R training3
 
Language R
Language RLanguage R
Language R
 
R training2
R training2R training2
R training2
 
Day 1b R structures objects.pptx
Day 1b   R structures   objects.pptxDay 1b   R structures   objects.pptx
Day 1b R structures objects.pptx
 
Datastructures in python
Datastructures in pythonDatastructures in python
Datastructures in python
 
3. R- list and data frame
3. R- list and data frame3. R- list and data frame
3. R- list and data frame
 
Big Data Mining in Indian Economic Survey 2017
Big Data Mining in Indian Economic Survey 2017Big Data Mining in Indian Economic Survey 2017
Big Data Mining in Indian Economic Survey 2017
 
Ggplot2 v3
Ggplot2 v3Ggplot2 v3
Ggplot2 v3
 
Arrays
ArraysArrays
Arrays
 
R workshop
R workshopR workshop
R workshop
 
Data Analysis and Programming in R
Data Analysis and Programming in RData Analysis and Programming in R
Data Analysis and Programming in R
 
Oracle sql ppt2
Oracle sql ppt2Oracle sql ppt2
Oracle sql ppt2
 
R language introduction
R language introductionR language introduction
R language introduction
 
Array
ArrayArray
Array
 
R_CheatSheet.pdf
R_CheatSheet.pdfR_CheatSheet.pdf
R_CheatSheet.pdf
 
R language tutorial.pptx
R language tutorial.pptxR language tutorial.pptx
R language tutorial.pptx
 
Arrays
ArraysArrays
Arrays
 
Unit 2 dsa LINEAR DATA STRUCTURE
Unit 2 dsa LINEAR DATA STRUCTUREUnit 2 dsa LINEAR DATA STRUCTURE
Unit 2 dsa LINEAR DATA STRUCTURE
 
Python 101++: Let's Get Down to Business!
Python 101++: Let's Get Down to Business!Python 101++: Let's Get Down to Business!
Python 101++: Let's Get Down to Business!
 

Mais de Ramakrishna Reddy Bijjam

Mais de Ramakrishna Reddy Bijjam (20)

Python Notes for mca i year students osmania university.docx
Python Notes for mca i year students osmania university.docxPython Notes for mca i year students osmania university.docx
Python Notes for mca i year students osmania university.docx
 
Arrays to arrays and pointers with arrays.pptx
Arrays to arrays and pointers with arrays.pptxArrays to arrays and pointers with arrays.pptx
Arrays to arrays and pointers with arrays.pptx
 
Auxiliary, Cache and Virtual memory.pptx
Auxiliary, Cache and Virtual memory.pptxAuxiliary, Cache and Virtual memory.pptx
Auxiliary, Cache and Virtual memory.pptx
 
Python With MongoDB in advanced Python.pptx
Python With MongoDB in advanced Python.pptxPython With MongoDB in advanced Python.pptx
Python With MongoDB in advanced Python.pptx
 
Pointers and single &multi dimentionalarrays.pptx
Pointers and single &multi dimentionalarrays.pptxPointers and single &multi dimentionalarrays.pptx
Pointers and single &multi dimentionalarrays.pptx
 
Certinity Factor and Dempster-shafer theory .pptx
Certinity Factor and Dempster-shafer theory .pptxCertinity Factor and Dempster-shafer theory .pptx
Certinity Factor and Dempster-shafer theory .pptx
 
Auxiliary Memory in computer Architecture.pptx
Auxiliary Memory in computer Architecture.pptxAuxiliary Memory in computer Architecture.pptx
Auxiliary Memory in computer Architecture.pptx
 
Random Forest Decision Tree.pptx
Random Forest Decision Tree.pptxRandom Forest Decision Tree.pptx
Random Forest Decision Tree.pptx
 
K Means Clustering in ML.pptx
K Means Clustering in ML.pptxK Means Clustering in ML.pptx
K Means Clustering in ML.pptx
 
Pandas.pptx
Pandas.pptxPandas.pptx
Pandas.pptx
 
Python With MongoDB.pptx
Python With MongoDB.pptxPython With MongoDB.pptx
Python With MongoDB.pptx
 
Python with MySql.pptx
Python with MySql.pptxPython with MySql.pptx
Python with MySql.pptx
 
PYTHON PROGRAMMING NOTES RKREDDY.pdf
PYTHON PROGRAMMING NOTES RKREDDY.pdfPYTHON PROGRAMMING NOTES RKREDDY.pdf
PYTHON PROGRAMMING NOTES RKREDDY.pdf
 
BInary file Operations.pptx
BInary file Operations.pptxBInary file Operations.pptx
BInary file Operations.pptx
 
Data Science in Python.pptx
Data Science in Python.pptxData Science in Python.pptx
Data Science in Python.pptx
 
CSV JSON and XML files in Python.pptx
CSV JSON and XML files in Python.pptxCSV JSON and XML files in Python.pptx
CSV JSON and XML files in Python.pptx
 
HTML files in python.pptx
HTML files in python.pptxHTML files in python.pptx
HTML files in python.pptx
 
Regular Expressions in Python.pptx
Regular Expressions in Python.pptxRegular Expressions in Python.pptx
Regular Expressions in Python.pptx
 
datareprersentation 1.pptx
datareprersentation 1.pptxdatareprersentation 1.pptx
datareprersentation 1.pptx
 
Apriori.pptx
Apriori.pptxApriori.pptx
Apriori.pptx
 

Último

Call Girls Indiranagar Just Call 👗 7737669865 👗 Top Class Call Girl Service B...
Call Girls Indiranagar Just Call 👗 7737669865 👗 Top Class Call Girl Service B...Call Girls Indiranagar Just Call 👗 7737669865 👗 Top Class Call Girl Service B...
Call Girls Indiranagar Just Call 👗 7737669865 👗 Top Class Call Girl Service B...
amitlee9823
 
Escorts Service Kumaraswamy Layout ☎ 7737669865☎ Book Your One night Stand (B...
Escorts Service Kumaraswamy Layout ☎ 7737669865☎ Book Your One night Stand (B...Escorts Service Kumaraswamy Layout ☎ 7737669865☎ Book Your One night Stand (B...
Escorts Service Kumaraswamy Layout ☎ 7737669865☎ Book Your One night Stand (B...
amitlee9823
 
Call Girls Hsr Layout Just Call 👗 7737669865 👗 Top Class Call Girl Service Ba...
Call Girls Hsr Layout Just Call 👗 7737669865 👗 Top Class Call Girl Service Ba...Call Girls Hsr Layout Just Call 👗 7737669865 👗 Top Class Call Girl Service Ba...
Call Girls Hsr Layout Just Call 👗 7737669865 👗 Top Class Call Girl Service Ba...
amitlee9823
 
Probability Grade 10 Third Quarter Lessons
Probability Grade 10 Third Quarter LessonsProbability Grade 10 Third Quarter Lessons
Probability Grade 10 Third Quarter Lessons
JoseMangaJr1
 
Vip Mumbai Call Girls Thane West Call On 9920725232 With Body to body massage...
Vip Mumbai Call Girls Thane West Call On 9920725232 With Body to body massage...Vip Mumbai Call Girls Thane West Call On 9920725232 With Body to body massage...
Vip Mumbai Call Girls Thane West Call On 9920725232 With Body to body massage...
amitlee9823
 
Call Girls In Bellandur ☎ 7737669865 🥵 Book Your One night Stand
Call Girls In Bellandur ☎ 7737669865 🥵 Book Your One night StandCall Girls In Bellandur ☎ 7737669865 🥵 Book Your One night Stand
Call Girls In Bellandur ☎ 7737669865 🥵 Book Your One night Stand
amitlee9823
 
FESE Capital Markets Fact Sheet 2024 Q1.pdf
FESE Capital Markets Fact Sheet 2024 Q1.pdfFESE Capital Markets Fact Sheet 2024 Q1.pdf
FESE Capital Markets Fact Sheet 2024 Q1.pdf
MarinCaroMartnezBerg
 

Último (20)

Ravak dropshipping via API with DroFx.pptx
Ravak dropshipping via API with DroFx.pptxRavak dropshipping via API with DroFx.pptx
Ravak dropshipping via API with DroFx.pptx
 
BDSM⚡Call Girls in Mandawali Delhi >༒8448380779 Escort Service
BDSM⚡Call Girls in Mandawali Delhi >༒8448380779 Escort ServiceBDSM⚡Call Girls in Mandawali Delhi >༒8448380779 Escort Service
BDSM⚡Call Girls in Mandawali Delhi >༒8448380779 Escort Service
 
Accredited-Transport-Cooperatives-Jan-2021-Web.pdf
Accredited-Transport-Cooperatives-Jan-2021-Web.pdfAccredited-Transport-Cooperatives-Jan-2021-Web.pdf
Accredited-Transport-Cooperatives-Jan-2021-Web.pdf
 
Call Girls Indiranagar Just Call 👗 7737669865 👗 Top Class Call Girl Service B...
Call Girls Indiranagar Just Call 👗 7737669865 👗 Top Class Call Girl Service B...Call Girls Indiranagar Just Call 👗 7737669865 👗 Top Class Call Girl Service B...
Call Girls Indiranagar Just Call 👗 7737669865 👗 Top Class Call Girl Service B...
 
Discover Why Less is More in B2B Research
Discover Why Less is More in B2B ResearchDiscover Why Less is More in B2B Research
Discover Why Less is More in B2B Research
 
VIP Model Call Girls Hinjewadi ( Pune ) Call ON 8005736733 Starting From 5K t...
VIP Model Call Girls Hinjewadi ( Pune ) Call ON 8005736733 Starting From 5K t...VIP Model Call Girls Hinjewadi ( Pune ) Call ON 8005736733 Starting From 5K t...
VIP Model Call Girls Hinjewadi ( Pune ) Call ON 8005736733 Starting From 5K t...
 
Sampling (random) method and Non random.ppt
Sampling (random) method and Non random.pptSampling (random) method and Non random.ppt
Sampling (random) method and Non random.ppt
 
Escorts Service Kumaraswamy Layout ☎ 7737669865☎ Book Your One night Stand (B...
Escorts Service Kumaraswamy Layout ☎ 7737669865☎ Book Your One night Stand (B...Escorts Service Kumaraswamy Layout ☎ 7737669865☎ Book Your One night Stand (B...
Escorts Service Kumaraswamy Layout ☎ 7737669865☎ Book Your One night Stand (B...
 
April 2024 - Crypto Market Report's Analysis
April 2024 - Crypto Market Report's AnalysisApril 2024 - Crypto Market Report's Analysis
April 2024 - Crypto Market Report's Analysis
 
Call Girls Hsr Layout Just Call 👗 7737669865 👗 Top Class Call Girl Service Ba...
Call Girls Hsr Layout Just Call 👗 7737669865 👗 Top Class Call Girl Service Ba...Call Girls Hsr Layout Just Call 👗 7737669865 👗 Top Class Call Girl Service Ba...
Call Girls Hsr Layout Just Call 👗 7737669865 👗 Top Class Call Girl Service Ba...
 
Probability Grade 10 Third Quarter Lessons
Probability Grade 10 Third Quarter LessonsProbability Grade 10 Third Quarter Lessons
Probability Grade 10 Third Quarter Lessons
 
Smarteg dropshipping via API with DroFx.pptx
Smarteg dropshipping via API with DroFx.pptxSmarteg dropshipping via API with DroFx.pptx
Smarteg dropshipping via API with DroFx.pptx
 
Midocean dropshipping via API with DroFx
Midocean dropshipping via API with DroFxMidocean dropshipping via API with DroFx
Midocean dropshipping via API with DroFx
 
ELKO dropshipping via API with DroFx.pptx
ELKO dropshipping via API with DroFx.pptxELKO dropshipping via API with DroFx.pptx
ELKO dropshipping via API with DroFx.pptx
 
Edukaciniai dropshipping via API with DroFx
Edukaciniai dropshipping via API with DroFxEdukaciniai dropshipping via API with DroFx
Edukaciniai dropshipping via API with DroFx
 
Anomaly detection and data imputation within time series
Anomaly detection and data imputation within time seriesAnomaly detection and data imputation within time series
Anomaly detection and data imputation within time series
 
(NEHA) Call Girls Katra Call Now 8617697112 Katra Escorts 24x7
(NEHA) Call Girls Katra Call Now 8617697112 Katra Escorts 24x7(NEHA) Call Girls Katra Call Now 8617697112 Katra Escorts 24x7
(NEHA) Call Girls Katra Call Now 8617697112 Katra Escorts 24x7
 
Vip Mumbai Call Girls Thane West Call On 9920725232 With Body to body massage...
Vip Mumbai Call Girls Thane West Call On 9920725232 With Body to body massage...Vip Mumbai Call Girls Thane West Call On 9920725232 With Body to body massage...
Vip Mumbai Call Girls Thane West Call On 9920725232 With Body to body massage...
 
Call Girls In Bellandur ☎ 7737669865 🥵 Book Your One night Stand
Call Girls In Bellandur ☎ 7737669865 🥵 Book Your One night StandCall Girls In Bellandur ☎ 7737669865 🥵 Book Your One night Stand
Call Girls In Bellandur ☎ 7737669865 🥵 Book Your One night Stand
 
FESE Capital Markets Fact Sheet 2024 Q1.pdf
FESE Capital Markets Fact Sheet 2024 Q1.pdfFESE Capital Markets Fact Sheet 2024 Q1.pdf
FESE Capital Markets Fact Sheet 2024 Q1.pdf
 

Factors.pptx

  • 1. FACTORS Factors are the data objects which are used to categorize the data and store it as levels. They can store both strings and integers. They are useful in the columns which have a limited number of unique values. Like "Male, "Female" and True, False etc. They are useful in data analysis for statistical modeling. Factors are created using the factor () function by taking a vector as input.
  • 2. • data <- c("East","West","East","North","North","East", "West","West","West","East","North") • print(data) print(is.factor(data)) • # Apply the factor function. • factor_data <- factor(data) • print(factor_data) • print(is.factor(factor_data))
  • 3. Factors in Data Frame • On creating any data frame with a column of text data, R treats the text column as categorical data and creates factors on it. • height <- c(132,151,162,139,166,147,122) • weight <- c(48,49,66,53,67,52,40) • gender <- c("male","male","female","female","male","female","male") • # Create the data frame. • input_data <- data.frame(height,weight,gender) print(input_data) • # Test if the gender column is a factor. print(is.factor(input_data$gender)) • # Print the gender column so see the levels. print(input_data$gender)
  • 4. Changing the Order of Levels • The order of the levels in a factor can be changed by applying the factor function again with new order of the levels. • data <- c("East","West","East","North","North","East","W est", "West","West","East","North") • factor_data <- f • new_order_data <- factor(factor_data,levels = c("East","West","North")) print(new_order_data)actor(data) print(factor_data)
  • 5. Generating Factor Levels • We can generate factor levels by using the gl() function. • It takes two integers as input which indicates how many levels and how many times • Syntax • gl(n, k, labels) Following is the description of the parameters used − • n is a integer giving the number of levels. • k is a integer giving the number of replications. • labels is a vector of labels for the resulting factor levels. • each level • Example • v <- gl(3, 4, labels = c("Tampa", "Seattle","Boston")) • print(v)
  • 6. Checking for a Factor in R • The function is.factor() is used to check whether the variable is a factor and returns “TRUE” if it is a factor. • gender <- factor(c("female", "male", "male", "female")); • print(is.factor(gender)) • Accessing elements of a Factor in R • Like we access elements of a vector, the same way we access the elements of a factor. If gender is a factor then gender[i] would mean accessing ith element in the factor. • Example: • gender <- factor(c("female", "male", "male", "female")); • gender[3] • gender <- factor(c("female", "male", "male", "female")); • gender[c(2, 4)] •
  • 7. Modification of a Factor in R • After a factor is formed, its components can be modified but the new values which need to be assigned must be at the predefined level. • Example: • gender <- factor(c("female", "male", "male", "female" )); • gender[2]<-"female" • gender • ender <- factor(c("female", "male", "male", "female" )); • • # add new level • levels(gender) <- c(levels(gender), "other") • gender[3] <- "other" • gender
  • 8. Factors in Data Frame • The Data frame is similar to a 2D array with the columns containing all the values of one variable and the rows having one set of values from every column. There are four things to remember about data frames: • column names are compulsory and cannot be empty. • Unique names should be assigned to each row. • The data frame’s data can be only of three types- factor, numeric, and character type. • The same number of data items must be present in each column. • In R language when we create a data frame, its column is categorical data and hence a factor is automatically created on it. We can create a data frame and check if its column is a factor.
  • 9. • Example: • age <- c(40, 49, 48, 40, 67, 52, 53) • salary <- c(103200, 106200, 150200, • 10606, 10390, 14070, 10220) • gender <- c("male", "male", "transgender", • "female", "male", "female", "transgender") • employee<- data.frame(age, salary, gender) • print(employee) • print(is.factor(employee$gender))
  • 10. • Gender<- sample(c("Male","Female"),20,replace=TRUE) • Values<-rnorm(20,mean=0,sd=1) • Group<-sample(letters[1:5],20,replace=TRUE) • • df<-data.frame(Gender,Values,Group) • library(ggplot2) • • # creating a boxplot • ggplot(df,aes(Gender,Values))+geom_boxplot(aes (fill=Group))
  • 11. LIST • Lists are the R objects which contain elements of different types like − numbers, strings, vectors and another list inside it. • A list can also contain a matrix or a function as its elements. • List is created using list() function. • Creating a List • Following is an example to create a list containing strings, numbers, vectors and a logical values. • # Create a list containing strings, numbers, vectors and a logical # values. • list_data <- list("Red", "Green", c(21,32,11), TRUE, 51.23, 119.1) • print(list_data)
  • 12. Naming List Elements • The list elements can be given names and they can be accessed using these names. • # Create a list containing a vector, a matrix and a list. • list_data <- list(c("Jan","Feb","Mar"), matrix(c(3,9,5,1,- 2,8), nrow = 2), list("green",12.3)) • # Give names to the elements in the list. names(list_data) <- c("1st Quarter", "A_Matrix", "A Inner list") • # Show the list. • print(list_data)
  • 13. Accessing List Elements • Elements of the list can be accessed by the index of the element in the list. In case of named lists it can also be accessed using the names. • We continue to use the list in the above example − • # Create a list containing a vector, a matrix and a list. • list_data <- list(c("Jan","Feb","Mar"), matrix(c(3,9,5,1,-2,8), nrow = 2), list("green",12.3)) • # Give names to the elements in the list. • names(list_data) <- c("1st Quarter", "A_Matrix", "A Inner list") • # Access the first element of the list. • print(list_data[1]) • # Access the thrid element. • As it is also a list, all its elements will be printed. • print(list_data[3]) • # Access the list element using the name of the element. print(list_data$A_Matrix)
  • 14. Manipulating List Elements • We can add, delete and update list elements as shown below. We can add and delete elements only at the end of a list. But we can update any element. • # Create a list containing a vector, a matrix and a list. • list_data <- list(c("Jan","Feb","Mar"), matrix(c(3,9,5,1,-2,8), nrow = 2), list("green",12.3)) • # Give names to the elements in the list. names(list_data) <- c("1st Quarter", "A_Matrix", "A Inner list") • # Add element at the end of the list. • list_data[4] <- "New element" print(list_data[4]) • # Remove the last element. • list_data[4] <- NULL • # Print the 4th Element. • print(list_data[4]) • # Update the 3rd Element. • list_data[3] <- "updated element" • print(list_data[3])
  • 15. Merging Lists • You can merge many lists into one list by placing all the lists inside one list() function • # Create two lists. list1 <- list(1,2,3) list2 <- list("Sun","Mon","Tue") # Merge the two lists. merged.list <- c(list1,list2) # Print the merged list. print(merged.list)
  • 16. Converting List to Vector • A list can be converted to a vector so that the elements of the vector can be used for further manipulation. All the arithmetic operations on vectors can be applied after the list is converted into vectors. To do this conversion, we use the unlist() function. It takes the list as input and produces a vector.
  • 17. • # Create lists. • list1 <- list(1:5) • print(list1) • list2 <-list(10:14) • print(list2) • # Convert the lists to vectors. • v1 <- unlist(list1) • v2 <- unlist(list2) • print(v1) • print(v2) • # Now add the vectors • result <- v1+v2 • print(result)