SlideShare a Scribd company logo
1 of 53
Introduction to R
Introduction – Rand RStudio
R:
• Ris acomputer language for statistical computing and is becomingthe
leading language in data science and statistics.
• T
oday,Ris the tool of choice for data scientists in every industryand
field.
• It open source freely available software and very widely usedby
professional statisticians.
• Rhasalarge collection of intermediate tools and excellent graphical
tools for dataanalysis.
RStudio:
• RStudioismore widely usedthanR
• RStudioisanIntegrated Development Environment (IDE)for R.
• It includesaconsole,syntax-highlighting editor thatsupports
direct codeexecutionaswell astools for plotting, history,
debugging& workspacemanagement.
Introduction –Rand RStudio
Installation
• RStudiorequires Rversion2.11.1orhigher.
• RStudioversion 0.99.902
• Latestversioncanbedownloaded from the linkbelow,
• https://www.rstudio.com/products/rstudio/download/
RCommandScreen
Basic RStudio commands
• ‘>’ iscalled theprompt
• If acommandistoo long to fiton aline, a+isusedfor the continuation
prompt.
Arithmetic Operators
Operator Function
+ Addition
- Subtraction
/ Division
* Multiplication
^ or** Exponentiation
Basic RStudio commands as Calculator
Examplesof arithmetic operationsinRStudio
Variable Assignment
Valuesareassignedto variableswith the assignmentoperator ’<-‘ or ‘=‘.
Functions
Rfunctions areinvokedbyits name,then followed bytheparenthesis, and
zeroor more arguments. Thefollowing commandcombinesfive numeric
valuesinto avector.
Extension Package
• Sometimes we need additional functionality beyond those offered by
the core Rlibrary.
• In order to install an extension package,you shouldinvoke
the install.packages function at the prompt and follow the instruction.
Or
• Select install packagesfrom Toolsdrop down menu
Install Packages
Install Packages
Enter the name of the packageyou want toinstall.
Getting Help
• Rprovides an inbuilt facility for getting more information onany
specific feature or namedfunction.
• For example, entering ?cor help(c) at the prompt givesdocumentation
of the function cinR.
• If there is no help available on any function or feature it displays an
error message.
• Bydefault the function help searches in the packageswhich are
loaded in memory.
• Thefunction try.all.packages allows searching all packages.
DataTypes
• In analysis of statistical data we use different types of data. For
manipulating suchdata, Rsupports following datatypes
- logical : It is aBoolean type data whose value canbe TRUEorFALSE.
- numeric : It canbe real orinteger.
- complex : It consists ofreal and imaginary numbers.
Logical
Alogical value is often created via comparison between variables.
Numeric
• Decimal values are called numeric in R.
• It is the default computational datatype.
• If we assignadecimal value to avariable xasfollows, xwill be of
numeric type.
Integer
• In order to create an integer variable in R,we needinvoke
the as.integer function. Wecan be assured that y is indeed aninteger
by applying the is.integerfunction.
• Wecancoerce anumeric value into an integer with the
sameas.integer function
Complex Numbers
Acomplex value in Ris defined via the pure imaginary valuei.
Character
• Acharacter object is used to represent string values in R.
• Weconvert objects into character valueswith
the as.character() function:
• Twocharacter values canbe concatenated with the pastefunction.
V
ectors
• Roperates on named data structures. Thesimplest suchstructureis
numeric vector.
• Numeric vector is asingle entity consisting of an ordered collectionof
numbers.
• T
ocreate avector named xcontaining 5 numbers 2,5,8,1,35 use
following command
This is assignment using function c().Assignment can also be made
by using assign function.
V
ector
• Avector cancontain character strings.
• Incidentally, the number of members in avector is givenby
the length function.
Combining Vectors
• Vectors canbe combined via the function c.
• For example, the following two vectors n and sare combined into a
new vector containing elements from bothvectors.
VectorArithmetic
• Arithmetic operations of vectors are performedmember-by-
member, i.e., member wise.
• For example, suppose we havetwo vectors aand b.
• Then, if we multiply aby 5, we would get avector with each ofits
members multiplied by 5.
• And if we add aand b together, the sum would be avector whose
members are the sum of the corresponding members from aandb.
VectorArithmetic
Recycling Rule
If two vectorsareof unequallength, the shorter onewill berecycledin
order to matchthe longer vector.Forexample,thefollowing
vectorsu andvhavedifferent lengths,andtheir sumiscomputedby
recyclingvaluesof the shorter vectoru.
VectorIndex
• Weretrieve valuesin avector bydeclaringanindex insideasingle
squarebracket "[]" operator.
• Forexample,the following showshow to retrieve avectormember.
VectorIndex
Negative Index
If the indexisnegative, it would stripthe memberwhoseposition has the
sameabsolutevalueasthe negative index.Forexample,the following
createsavector slicewith the thirdmember removed.
Out-of-Range Index
If anindex isout-of-range, amissingvaluewill bereported viathe
symbolNA.
Numeric IndexVector
• Anew vector canbe sliced from agiven vector with anumeric index
vector, which consists of member positions of the original vector to be
retrieved.
• Here it shows how toretrieve avector slice containing the second and
third members of agivenvector’s.
Numeric IndexVector
Duplicate Indexes
Out-of-OrderIndexes
Range Index
29
Named VectorMembers
• Wecanassignnamesto vector members.
• For example, the following variable v is acharacter string vector
with two members.
• Wenow name the first member asFirst, and the second asLast.
Named VectorMembers
• Thenwe can retrieve the first member by itsname.
• Furthermore, we canreverse the order with acharacter stringindex
vector.
Matrix
• Amatrix is acollection of data elements arranged in atwo-
dimensional rectangular layout. Thefollowing is an example of amatrix
with 2 rows and 3columns.
• Wereproduce amemory representation of the matrix in Rwith
the matrix function.
Matrix
Thedata elements must be of the samebasictype.
• An element at the mth row, nth column of Acanbe accessedby the
expressionA[m, n].
• Theentire mth row Acan be extracted asA[m,].
• Similarly, the entire nth column Acanbe extracted asA[,n].
Wecanalsoextract more than onerowsor columnsat atime.
• If we assign names to the rows and columns of the matrix, than we can
accessthe elements by names.
Matrix Construction
• There are various waysto construct amatrix. When we construct a
matrix directly with data elements, the matrix content is filled along
the column orientation bydefault.
• For example, in the following code snippet, the content of Bisfilled
along the columnsconsecutively.
Matrix Transpose
• Weconstruct the transpose of amatrix by interchanging itscolumns
and rows with the function t .
Combining Matrices
• The columns of two matrices having the same number of rows can be
combined into a larger matrix. For example, suppose we have another
matrix Calso with 3rows.
• Thenwe can combine the columns of Band Cwith cbind.
• Similarly, we cancombine the rows of two matrices ifthey havethe
samenumber of columns with the rbindfunction.
Deconstruction
• Wecandeconstruct amatrix by applying the cfunction, which
combines all column vectors into one
TheWorkspace
• Theworkspace is your current Rworking environment and includes
any user-defined objects (vectors, matrices, data frames, lists,
functions).
• At the end of an Rsession, the user can savean image of thecurrent
workspace that is automatically reloaded the next time Risstarted.
• Commandsare entered interactively at the Ruserprompt.
• Up and down arrow keys scroll through your commandhistory.
TheWorkspace
• Y
ouwill probably want to keep different projects indifferent physical
directories. Here are some standard commands for managing your
workspace.
IMPORT
ANTNOTEFORWINDOWS USERS:
• Rgets confused if you useapath in your codelike
c:mydocumentsmyfile.txt
• This is because Rsees"" asan escapecharacter. Instead,use
c:/mydocuments/myfile.txt
RCommand for WorkingDirectory
# work with your previouscommands
# saveyour command history
RCommand forWorkingDirectory
# recall your command history
Data Frame
• Adata frame is used for storing data tables. It is alist ofvectors of
equal length.
Example :
Following are the height (in cms)and weight (in kgs) of10 boys.
Prepare adata frame of height andweight.
ImportingData
• Importing data into Ris fairlysimple.
CommaDelimited File (.CSV extension)
TextFile(.txt extension)
FromExcel (.xlsx Extension)
• One of the best ways to read an Excel file is to export it to acomma
delimited file and import itusing the method above.
• Alternatively you can usethe xlsx packageto accessExcelfiles. The
first row should contain variable/columnnames.
• read in the first worksheet from the workbook myexcel.xlsx
• first row contains variable names
• read in the worksheet namedmysheet
FromSAS
• SaveSASdataset in trasport format
libname out xport 'c:/mydata.xpt';
data out.mydata;
set sasuser.mydata;
run;
• In R
# character variables are converted to Rfactors
Sorting Data
• T
osort adata frame in R,use the order( )function.
• Bydefault, sorting is ASCENDING.Prepend the sorting variable bya
minus sign to indicate DESCENDINGorder.
Here are some examples.
Sorting examples using the mtcarsdataset
# sort bympg
Sorting Data
• # sort by mpg andcyl
• #sort by mpg (ascending) and cyl(descending)
Renaming Variable (Header)
T
oExit R:
T
orename avariable:
ThankY
ou

More Related Content

Similar to Introduction to R.pptx

Unit I - 1R introduction to R program.pptx
Unit I - 1R introduction to R program.pptxUnit I - 1R introduction to R program.pptx
Unit I - 1R introduction to R program.pptxSreeLaya9
 
CS4443 - Modern Programming Language - I Lecture (2)
CS4443 - Modern Programming Language - I  Lecture (2)CS4443 - Modern Programming Language - I  Lecture (2)
CS4443 - Modern Programming Language - I Lecture (2)Dilawar Khan
 
Q-Step_WS_06112019_Data_Analysis_and_visualisation_with_Python.pptx
Q-Step_WS_06112019_Data_Analysis_and_visualisation_with_Python.pptxQ-Step_WS_06112019_Data_Analysis_and_visualisation_with_Python.pptx
Q-Step_WS_06112019_Data_Analysis_and_visualisation_with_Python.pptxkalai75
 
Console I/o & basics of array and strings.pptx
Console I/o & basics of array and strings.pptxConsole I/o & basics of array and strings.pptx
Console I/o & basics of array and strings.pptxPRASENJITMORE2
 
Unit 2 Principles of Programming Languages
Unit 2 Principles of Programming LanguagesUnit 2 Principles of Programming Languages
Unit 2 Principles of Programming LanguagesVasavi College of Engg
 
Engineering CS 5th Sem Python Module -2.pptx
Engineering CS 5th Sem Python Module -2.pptxEngineering CS 5th Sem Python Module -2.pptx
Engineering CS 5th Sem Python Module -2.pptxhardii0991
 
Unit I - introduction to r language 2.pptx
Unit I - introduction to r language 2.pptxUnit I - introduction to r language 2.pptx
Unit I - introduction to r language 2.pptxSreeLaya9
 
Programming in python
Programming in pythonProgramming in python
Programming in pythonIvan Rojas
 
Learn ActionScript programming myassignmenthelp.net
Learn ActionScript programming myassignmenthelp.netLearn ActionScript programming myassignmenthelp.net
Learn ActionScript programming myassignmenthelp.netwww.myassignmenthelp.net
 

Similar to Introduction to R.pptx (20)

Unit I - 1R introduction to R program.pptx
Unit I - 1R introduction to R program.pptxUnit I - 1R introduction to R program.pptx
Unit I - 1R introduction to R program.pptx
 
Aggregate.pptx
Aggregate.pptxAggregate.pptx
Aggregate.pptx
 
CS4443 - Modern Programming Language - I Lecture (2)
CS4443 - Modern Programming Language - I  Lecture (2)CS4443 - Modern Programming Language - I  Lecture (2)
CS4443 - Modern Programming Language - I Lecture (2)
 
Q-Step_WS_06112019_Data_Analysis_and_visualisation_with_Python.pptx
Q-Step_WS_06112019_Data_Analysis_and_visualisation_with_Python.pptxQ-Step_WS_06112019_Data_Analysis_and_visualisation_with_Python.pptx
Q-Step_WS_06112019_Data_Analysis_and_visualisation_with_Python.pptx
 
محاضرة برنامج التحليل الكمي R program د.هديل القفيدي
محاضرة برنامج التحليل الكمي   R program د.هديل القفيديمحاضرة برنامج التحليل الكمي   R program د.هديل القفيدي
محاضرة برنامج التحليل الكمي R program د.هديل القفيدي
 
Console I/o & basics of array and strings.pptx
Console I/o & basics of array and strings.pptxConsole I/o & basics of array and strings.pptx
Console I/o & basics of array and strings.pptx
 
Unit 2 Principles of Programming Languages
Unit 2 Principles of Programming LanguagesUnit 2 Principles of Programming Languages
Unit 2 Principles of Programming Languages
 
Data structure
Data structureData structure
Data structure
 
Engineering CS 5th Sem Python Module -2.pptx
Engineering CS 5th Sem Python Module -2.pptxEngineering CS 5th Sem Python Module -2.pptx
Engineering CS 5th Sem Python Module -2.pptx
 
Unit I - introduction to r language 2.pptx
Unit I - introduction to r language 2.pptxUnit I - introduction to r language 2.pptx
Unit I - introduction to r language 2.pptx
 
Programming in python
Programming in pythonProgramming in python
Programming in python
 
محاضرة برنامج التحليل الكمي R program د.هديل القفيدي
محاضرة برنامج التحليل الكمي   R program د.هديل القفيديمحاضرة برنامج التحليل الكمي   R program د.هديل القفيدي
محاضرة برنامج التحليل الكمي R program د.هديل القفيدي
 
Mbd dd
Mbd ddMbd dd
Mbd dd
 
Project
ProjectProject
Project
 
Python
PythonPython
Python
 
Learn ActionScript programming myassignmenthelp.net
Learn ActionScript programming myassignmenthelp.netLearn ActionScript programming myassignmenthelp.net
Learn ActionScript programming myassignmenthelp.net
 
arrays.pptx
arrays.pptxarrays.pptx
arrays.pptx
 
R training2
R training2R training2
R training2
 
Chapter-Five.pptx
Chapter-Five.pptxChapter-Five.pptx
Chapter-Five.pptx
 
Pandas csv
Pandas csvPandas csv
Pandas csv
 

More from RohithK65

orific meter.pptx
orific meter.pptxorific meter.pptx
orific meter.pptxRohithK65
 
Module_3_Data Compression Techniques.pptx
Module_3_Data Compression Techniques.pptxModule_3_Data Compression Techniques.pptx
Module_3_Data Compression Techniques.pptxRohithK65
 
Photovoltaic and wind 1.pptx
Photovoltaic and wind 1.pptxPhotovoltaic and wind 1.pptx
Photovoltaic and wind 1.pptxRohithK65
 
BIOINFO.pptx
BIOINFO.pptxBIOINFO.pptx
BIOINFO.pptxRohithK65
 
Flow Injection Analysis Final.pptx
Flow Injection Analysis Final.pptxFlow Injection Analysis Final.pptx
Flow Injection Analysis Final.pptxRohithK65
 
ppt pawan_merged.pdf
ppt pawan_merged.pdfppt pawan_merged.pdf
ppt pawan_merged.pdfRohithK65
 
SNPs and ESTs.pptx
SNPs and ESTs.pptxSNPs and ESTs.pptx
SNPs and ESTs.pptxRohithK65
 
Cofactor and Coenzyme.ppt
Cofactor and Coenzyme.pptCofactor and Coenzyme.ppt
Cofactor and Coenzyme.pptRohithK65
 

More from RohithK65 (10)

orific meter.pptx
orific meter.pptxorific meter.pptx
orific meter.pptx
 
Module_3_Data Compression Techniques.pptx
Module_3_Data Compression Techniques.pptxModule_3_Data Compression Techniques.pptx
Module_3_Data Compression Techniques.pptx
 
Photovoltaic and wind 1.pptx
Photovoltaic and wind 1.pptxPhotovoltaic and wind 1.pptx
Photovoltaic and wind 1.pptx
 
BIOINFO.pptx
BIOINFO.pptxBIOINFO.pptx
BIOINFO.pptx
 
qsar.pptx
qsar.pptxqsar.pptx
qsar.pptx
 
Flow Injection Analysis Final.pptx
Flow Injection Analysis Final.pptxFlow Injection Analysis Final.pptx
Flow Injection Analysis Final.pptx
 
ppt pawan_merged.pdf
ppt pawan_merged.pdfppt pawan_merged.pdf
ppt pawan_merged.pdf
 
d-2.pptx
 d-2.pptx d-2.pptx
d-2.pptx
 
SNPs and ESTs.pptx
SNPs and ESTs.pptxSNPs and ESTs.pptx
SNPs and ESTs.pptx
 
Cofactor and Coenzyme.ppt
Cofactor and Coenzyme.pptCofactor and Coenzyme.ppt
Cofactor and Coenzyme.ppt
 

Recently uploaded

Introduction to ArtificiaI Intelligence in Higher Education
Introduction to ArtificiaI Intelligence in Higher EducationIntroduction to ArtificiaI Intelligence in Higher Education
Introduction to ArtificiaI Intelligence in Higher Educationpboyjonauth
 
Alper Gobel In Media Res Media Component
Alper Gobel In Media Res Media ComponentAlper Gobel In Media Res Media Component
Alper Gobel In Media Res Media ComponentInMediaRes1
 
Pharmacognosy Flower 3. Compositae 2023.pdf
Pharmacognosy Flower 3. Compositae 2023.pdfPharmacognosy Flower 3. Compositae 2023.pdf
Pharmacognosy Flower 3. Compositae 2023.pdfMahmoud M. Sallam
 
Computed Fields and api Depends in the Odoo 17
Computed Fields and api Depends in the Odoo 17Computed Fields and api Depends in the Odoo 17
Computed Fields and api Depends in the Odoo 17Celine George
 
Incoming and Outgoing Shipments in 1 STEP Using Odoo 17
Incoming and Outgoing Shipments in 1 STEP Using Odoo 17Incoming and Outgoing Shipments in 1 STEP Using Odoo 17
Incoming and Outgoing Shipments in 1 STEP Using Odoo 17Celine George
 
18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdf
18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdf18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdf
18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdfssuser54595a
 
Full Stack Web Development Course for Beginners
Full Stack Web Development Course  for BeginnersFull Stack Web Development Course  for Beginners
Full Stack Web Development Course for BeginnersSabitha Banu
 
Interactive Powerpoint_How to Master effective communication
Interactive Powerpoint_How to Master effective communicationInteractive Powerpoint_How to Master effective communication
Interactive Powerpoint_How to Master effective communicationnomboosow
 
Employee wellbeing at the workplace.pptx
Employee wellbeing at the workplace.pptxEmployee wellbeing at the workplace.pptx
Employee wellbeing at the workplace.pptxNirmalaLoungPoorunde1
 
CARE OF CHILD IN INCUBATOR..........pptx
CARE OF CHILD IN INCUBATOR..........pptxCARE OF CHILD IN INCUBATOR..........pptx
CARE OF CHILD IN INCUBATOR..........pptxGaneshChakor2
 
Painted Grey Ware.pptx, PGW Culture of India
Painted Grey Ware.pptx, PGW Culture of IndiaPainted Grey Ware.pptx, PGW Culture of India
Painted Grey Ware.pptx, PGW Culture of IndiaVirag Sontakke
 
Organic Name Reactions for the students and aspirants of Chemistry12th.pptx
Organic Name Reactions  for the students and aspirants of Chemistry12th.pptxOrganic Name Reactions  for the students and aspirants of Chemistry12th.pptx
Organic Name Reactions for the students and aspirants of Chemistry12th.pptxVS Mahajan Coaching Centre
 
Presiding Officer Training module 2024 lok sabha elections
Presiding Officer Training module 2024 lok sabha electionsPresiding Officer Training module 2024 lok sabha elections
Presiding Officer Training module 2024 lok sabha electionsanshu789521
 
Meghan Sutherland In Media Res Media Component
Meghan Sutherland In Media Res Media ComponentMeghan Sutherland In Media Res Media Component
Meghan Sutherland In Media Res Media ComponentInMediaRes1
 
KSHARA STURA .pptx---KSHARA KARMA THERAPY (CAUSTIC THERAPY)————IMP.OF KSHARA ...
KSHARA STURA .pptx---KSHARA KARMA THERAPY (CAUSTIC THERAPY)————IMP.OF KSHARA ...KSHARA STURA .pptx---KSHARA KARMA THERAPY (CAUSTIC THERAPY)————IMP.OF KSHARA ...
KSHARA STURA .pptx---KSHARA KARMA THERAPY (CAUSTIC THERAPY)————IMP.OF KSHARA ...M56BOOKSTORE PRODUCT/SERVICE
 
Software Engineering Methodologies (overview)
Software Engineering Methodologies (overview)Software Engineering Methodologies (overview)
Software Engineering Methodologies (overview)eniolaolutunde
 
Biting mechanism of poisonous snakes.pdf
Biting mechanism of poisonous snakes.pdfBiting mechanism of poisonous snakes.pdf
Biting mechanism of poisonous snakes.pdfadityarao40181
 
How to Make a Pirate ship Primary Education.pptx
How to Make a Pirate ship Primary Education.pptxHow to Make a Pirate ship Primary Education.pptx
How to Make a Pirate ship Primary Education.pptxmanuelaromero2013
 
Enzyme, Pharmaceutical Aids, Miscellaneous Last Part of Chapter no 5th.pdf
Enzyme, Pharmaceutical Aids, Miscellaneous Last Part of Chapter no 5th.pdfEnzyme, Pharmaceutical Aids, Miscellaneous Last Part of Chapter no 5th.pdf
Enzyme, Pharmaceutical Aids, Miscellaneous Last Part of Chapter no 5th.pdfSumit Tiwari
 

Recently uploaded (20)

Introduction to ArtificiaI Intelligence in Higher Education
Introduction to ArtificiaI Intelligence in Higher EducationIntroduction to ArtificiaI Intelligence in Higher Education
Introduction to ArtificiaI Intelligence in Higher Education
 
Alper Gobel In Media Res Media Component
Alper Gobel In Media Res Media ComponentAlper Gobel In Media Res Media Component
Alper Gobel In Media Res Media Component
 
Pharmacognosy Flower 3. Compositae 2023.pdf
Pharmacognosy Flower 3. Compositae 2023.pdfPharmacognosy Flower 3. Compositae 2023.pdf
Pharmacognosy Flower 3. Compositae 2023.pdf
 
Computed Fields and api Depends in the Odoo 17
Computed Fields and api Depends in the Odoo 17Computed Fields and api Depends in the Odoo 17
Computed Fields and api Depends in the Odoo 17
 
Incoming and Outgoing Shipments in 1 STEP Using Odoo 17
Incoming and Outgoing Shipments in 1 STEP Using Odoo 17Incoming and Outgoing Shipments in 1 STEP Using Odoo 17
Incoming and Outgoing Shipments in 1 STEP Using Odoo 17
 
18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdf
18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdf18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdf
18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdf
 
Full Stack Web Development Course for Beginners
Full Stack Web Development Course  for BeginnersFull Stack Web Development Course  for Beginners
Full Stack Web Development Course for Beginners
 
Interactive Powerpoint_How to Master effective communication
Interactive Powerpoint_How to Master effective communicationInteractive Powerpoint_How to Master effective communication
Interactive Powerpoint_How to Master effective communication
 
Employee wellbeing at the workplace.pptx
Employee wellbeing at the workplace.pptxEmployee wellbeing at the workplace.pptx
Employee wellbeing at the workplace.pptx
 
CARE OF CHILD IN INCUBATOR..........pptx
CARE OF CHILD IN INCUBATOR..........pptxCARE OF CHILD IN INCUBATOR..........pptx
CARE OF CHILD IN INCUBATOR..........pptx
 
Painted Grey Ware.pptx, PGW Culture of India
Painted Grey Ware.pptx, PGW Culture of IndiaPainted Grey Ware.pptx, PGW Culture of India
Painted Grey Ware.pptx, PGW Culture of India
 
Organic Name Reactions for the students and aspirants of Chemistry12th.pptx
Organic Name Reactions  for the students and aspirants of Chemistry12th.pptxOrganic Name Reactions  for the students and aspirants of Chemistry12th.pptx
Organic Name Reactions for the students and aspirants of Chemistry12th.pptx
 
Presiding Officer Training module 2024 lok sabha elections
Presiding Officer Training module 2024 lok sabha electionsPresiding Officer Training module 2024 lok sabha elections
Presiding Officer Training module 2024 lok sabha elections
 
Meghan Sutherland In Media Res Media Component
Meghan Sutherland In Media Res Media ComponentMeghan Sutherland In Media Res Media Component
Meghan Sutherland In Media Res Media Component
 
Model Call Girl in Bikash Puri Delhi reach out to us at 🔝9953056974🔝
Model Call Girl in Bikash Puri  Delhi reach out to us at 🔝9953056974🔝Model Call Girl in Bikash Puri  Delhi reach out to us at 🔝9953056974🔝
Model Call Girl in Bikash Puri Delhi reach out to us at 🔝9953056974🔝
 
KSHARA STURA .pptx---KSHARA KARMA THERAPY (CAUSTIC THERAPY)————IMP.OF KSHARA ...
KSHARA STURA .pptx---KSHARA KARMA THERAPY (CAUSTIC THERAPY)————IMP.OF KSHARA ...KSHARA STURA .pptx---KSHARA KARMA THERAPY (CAUSTIC THERAPY)————IMP.OF KSHARA ...
KSHARA STURA .pptx---KSHARA KARMA THERAPY (CAUSTIC THERAPY)————IMP.OF KSHARA ...
 
Software Engineering Methodologies (overview)
Software Engineering Methodologies (overview)Software Engineering Methodologies (overview)
Software Engineering Methodologies (overview)
 
Biting mechanism of poisonous snakes.pdf
Biting mechanism of poisonous snakes.pdfBiting mechanism of poisonous snakes.pdf
Biting mechanism of poisonous snakes.pdf
 
How to Make a Pirate ship Primary Education.pptx
How to Make a Pirate ship Primary Education.pptxHow to Make a Pirate ship Primary Education.pptx
How to Make a Pirate ship Primary Education.pptx
 
Enzyme, Pharmaceutical Aids, Miscellaneous Last Part of Chapter no 5th.pdf
Enzyme, Pharmaceutical Aids, Miscellaneous Last Part of Chapter no 5th.pdfEnzyme, Pharmaceutical Aids, Miscellaneous Last Part of Chapter no 5th.pdf
Enzyme, Pharmaceutical Aids, Miscellaneous Last Part of Chapter no 5th.pdf
 

Introduction to R.pptx

  • 2. Introduction – Rand RStudio R: • Ris acomputer language for statistical computing and is becomingthe leading language in data science and statistics. • T oday,Ris the tool of choice for data scientists in every industryand field. • It open source freely available software and very widely usedby professional statisticians. • Rhasalarge collection of intermediate tools and excellent graphical tools for dataanalysis.
  • 3. RStudio: • RStudioismore widely usedthanR • RStudioisanIntegrated Development Environment (IDE)for R. • It includesaconsole,syntax-highlighting editor thatsupports direct codeexecutionaswell astools for plotting, history, debugging& workspacemanagement. Introduction –Rand RStudio
  • 4. Installation • RStudiorequires Rversion2.11.1orhigher. • RStudioversion 0.99.902 • Latestversioncanbedownloaded from the linkbelow, • https://www.rstudio.com/products/rstudio/download/
  • 6. Basic RStudio commands • ‘>’ iscalled theprompt • If acommandistoo long to fiton aline, a+isusedfor the continuation prompt. Arithmetic Operators Operator Function + Addition - Subtraction / Division * Multiplication ^ or** Exponentiation
  • 7. Basic RStudio commands as Calculator Examplesof arithmetic operationsinRStudio
  • 8. Variable Assignment Valuesareassignedto variableswith the assignmentoperator ’<-‘ or ‘=‘.
  • 9. Functions Rfunctions areinvokedbyits name,then followed bytheparenthesis, and zeroor more arguments. Thefollowing commandcombinesfive numeric valuesinto avector.
  • 10. Extension Package • Sometimes we need additional functionality beyond those offered by the core Rlibrary. • In order to install an extension package,you shouldinvoke the install.packages function at the prompt and follow the instruction. Or • Select install packagesfrom Toolsdrop down menu
  • 12. Install Packages Enter the name of the packageyou want toinstall.
  • 13. Getting Help • Rprovides an inbuilt facility for getting more information onany specific feature or namedfunction. • For example, entering ?cor help(c) at the prompt givesdocumentation of the function cinR. • If there is no help available on any function or feature it displays an error message. • Bydefault the function help searches in the packageswhich are loaded in memory. • Thefunction try.all.packages allows searching all packages.
  • 14. DataTypes • In analysis of statistical data we use different types of data. For manipulating suchdata, Rsupports following datatypes - logical : It is aBoolean type data whose value canbe TRUEorFALSE. - numeric : It canbe real orinteger. - complex : It consists ofreal and imaginary numbers.
  • 15. Logical Alogical value is often created via comparison between variables.
  • 16. Numeric • Decimal values are called numeric in R. • It is the default computational datatype. • If we assignadecimal value to avariable xasfollows, xwill be of numeric type.
  • 17. Integer • In order to create an integer variable in R,we needinvoke the as.integer function. Wecan be assured that y is indeed aninteger by applying the is.integerfunction. • Wecancoerce anumeric value into an integer with the sameas.integer function
  • 18. Complex Numbers Acomplex value in Ris defined via the pure imaginary valuei.
  • 19. Character • Acharacter object is used to represent string values in R. • Weconvert objects into character valueswith the as.character() function: • Twocharacter values canbe concatenated with the pastefunction.
  • 20. V ectors • Roperates on named data structures. Thesimplest suchstructureis numeric vector. • Numeric vector is asingle entity consisting of an ordered collectionof numbers. • T ocreate avector named xcontaining 5 numbers 2,5,8,1,35 use following command This is assignment using function c().Assignment can also be made by using assign function.
  • 21. V ector • Avector cancontain character strings. • Incidentally, the number of members in avector is givenby the length function.
  • 22. Combining Vectors • Vectors canbe combined via the function c. • For example, the following two vectors n and sare combined into a new vector containing elements from bothvectors.
  • 23. VectorArithmetic • Arithmetic operations of vectors are performedmember-by- member, i.e., member wise. • For example, suppose we havetwo vectors aand b. • Then, if we multiply aby 5, we would get avector with each ofits members multiplied by 5. • And if we add aand b together, the sum would be avector whose members are the sum of the corresponding members from aandb.
  • 24. VectorArithmetic Recycling Rule If two vectorsareof unequallength, the shorter onewill berecycledin order to matchthe longer vector.Forexample,thefollowing vectorsu andvhavedifferent lengths,andtheir sumiscomputedby recyclingvaluesof the shorter vectoru.
  • 25. VectorIndex • Weretrieve valuesin avector bydeclaringanindex insideasingle squarebracket "[]" operator. • Forexample,the following showshow to retrieve avectormember.
  • 26. VectorIndex Negative Index If the indexisnegative, it would stripthe memberwhoseposition has the sameabsolutevalueasthe negative index.Forexample,the following createsavector slicewith the thirdmember removed. Out-of-Range Index If anindex isout-of-range, amissingvaluewill bereported viathe symbolNA.
  • 27. Numeric IndexVector • Anew vector canbe sliced from agiven vector with anumeric index vector, which consists of member positions of the original vector to be retrieved. • Here it shows how toretrieve avector slice containing the second and third members of agivenvector’s.
  • 29. 29 Named VectorMembers • Wecanassignnamesto vector members. • For example, the following variable v is acharacter string vector with two members. • Wenow name the first member asFirst, and the second asLast.
  • 30. Named VectorMembers • Thenwe can retrieve the first member by itsname. • Furthermore, we canreverse the order with acharacter stringindex vector.
  • 31. Matrix • Amatrix is acollection of data elements arranged in atwo- dimensional rectangular layout. Thefollowing is an example of amatrix with 2 rows and 3columns. • Wereproduce amemory representation of the matrix in Rwith the matrix function.
  • 32. Matrix Thedata elements must be of the samebasictype.
  • 33. • An element at the mth row, nth column of Acanbe accessedby the expressionA[m, n]. • Theentire mth row Acan be extracted asA[m,]. • Similarly, the entire nth column Acanbe extracted asA[,n].
  • 34. Wecanalsoextract more than onerowsor columnsat atime.
  • 35. • If we assign names to the rows and columns of the matrix, than we can accessthe elements by names.
  • 36. Matrix Construction • There are various waysto construct amatrix. When we construct a matrix directly with data elements, the matrix content is filled along the column orientation bydefault. • For example, in the following code snippet, the content of Bisfilled along the columnsconsecutively.
  • 37. Matrix Transpose • Weconstruct the transpose of amatrix by interchanging itscolumns and rows with the function t .
  • 38. Combining Matrices • The columns of two matrices having the same number of rows can be combined into a larger matrix. For example, suppose we have another matrix Calso with 3rows.
  • 39. • Thenwe can combine the columns of Band Cwith cbind.
  • 40. • Similarly, we cancombine the rows of two matrices ifthey havethe samenumber of columns with the rbindfunction.
  • 41. Deconstruction • Wecandeconstruct amatrix by applying the cfunction, which combines all column vectors into one
  • 42. TheWorkspace • Theworkspace is your current Rworking environment and includes any user-defined objects (vectors, matrices, data frames, lists, functions). • At the end of an Rsession, the user can savean image of thecurrent workspace that is automatically reloaded the next time Risstarted. • Commandsare entered interactively at the Ruserprompt. • Up and down arrow keys scroll through your commandhistory.
  • 43. TheWorkspace • Y ouwill probably want to keep different projects indifferent physical directories. Here are some standard commands for managing your workspace. IMPORT ANTNOTEFORWINDOWS USERS: • Rgets confused if you useapath in your codelike c:mydocumentsmyfile.txt • This is because Rsees"" asan escapecharacter. Instead,use c:/mydocuments/myfile.txt
  • 44. RCommand for WorkingDirectory # work with your previouscommands # saveyour command history
  • 46. Data Frame • Adata frame is used for storing data tables. It is alist ofvectors of equal length. Example : Following are the height (in cms)and weight (in kgs) of10 boys. Prepare adata frame of height andweight.
  • 47. ImportingData • Importing data into Ris fairlysimple. CommaDelimited File (.CSV extension) TextFile(.txt extension)
  • 48. FromExcel (.xlsx Extension) • One of the best ways to read an Excel file is to export it to acomma delimited file and import itusing the method above. • Alternatively you can usethe xlsx packageto accessExcelfiles. The first row should contain variable/columnnames. • read in the first worksheet from the workbook myexcel.xlsx • first row contains variable names • read in the worksheet namedmysheet
  • 49. FromSAS • SaveSASdataset in trasport format libname out xport 'c:/mydata.xpt'; data out.mydata; set sasuser.mydata; run; • In R # character variables are converted to Rfactors
  • 50. Sorting Data • T osort adata frame in R,use the order( )function. • Bydefault, sorting is ASCENDING.Prepend the sorting variable bya minus sign to indicate DESCENDINGorder. Here are some examples. Sorting examples using the mtcarsdataset # sort bympg
  • 51. Sorting Data • # sort by mpg andcyl • #sort by mpg (ascending) and cyl(descending)
  • 52. Renaming Variable (Header) T oExit R: T orename avariable: