SlideShare a Scribd company logo
1 of 18
DATA FILES, BLOCKS OF
EXPRESSIONS, CYCLES AND
FUNCTIONS IN R
Vladimir Bakhrushin,
Professor, D.Sc. (Phys. & Math.)
Vladimir.Bakhrushin@gmail.com
Data reading
> data<-read.table(“File name", sep=";", dec=",",
header=TRUE, …)
 first argument is a reference to the file of *.csv format, that
contains data;
 argument sep indicates, by which sign the data are separated;
 argument dec indicates decimal separator for numbers;
 argument header indicates whether the first cells of each
column are the column names;
 argument row.names indicates whether one of columns
contains the row names;
 argument nrows specifies the number of lines that need to be
read from the table.
Data reading
Writing data to a file
write.table(x, file = "", append = FALSE, quote = TRUE, sep = "
", na = "NA", dec = ".", row.names = TRUE, col.names = TRUE,
qmethod = c("escape", "double"), …)
 x – object that must be written to the file (usually it is a matrix
or data table);
 file – name of the file to which the data must be written or
other connections opened to writing;
 append – argument that indicates the need to append data to
an existing file or to create a new file with the same name;
 quote – indicates the need to take in quotes marks of rows
and columns;
 na – character set used for the missing values.
Writing data to a file
write.table(a2, file = "a2.csv", sep =
" ", dec = ".")
Lists
For saving of heterogeneous data in the one object lists can be
used. For example:
> x1 = c("Milk", "Yogurt", "Sour cream", "Curd")
> x2 = c(1, 1, 14, 7)
> x3 = c(TRUE, FALSE)
> l1 = list(Text = x1, Number = x2, Logic = x3)
> l1
To identify specific elements of the list such constructions can be
used :
 l1$Text[3]; l1$Text;
 l1[[1]][2]; l1[[2]].
Lists
Data frames
Data editing using function fix()
Comments, blocks of expressions
Any comment begins with the character #. The test located in
the line after this character not regarded as part of the program
to be executed.
Expressions can be combined into blocks with curly braces.
The result of the expressions block is the result of the last of
them.
> {
+ x = 9;
+ y = 4;
+ x + y;
+ }
[1] 13
Conditional constructs
“If” – “else” statement is an example of conditional construct:
if (<condition>)
{<expression_1>
}else{
<expression_2>}
Loops
Loops with predetermined number of iterations can be
organized using function “for”:
for (<variable> in <expression_1>)
<expression_2>
If it is need to repeat iterations until a certain condition is
fulfilled, we can use a loop “while”:
while (<condition>) {
<expression>
}
Loops
Loops
Infinite loops “Repeat” are
used when a procedure
should be executed if the
interruption condition is not
performed. Command
“break” is used to interrupt
the cycle, and command
“next” – to interrupt the
current iteration and move to
the next one.
Functions
Function in R is an object, that for a given set of arguments
returns a certain value. Usually when the function is declared its
value is assigned to some variable.
<variabe> = function(<arguments>)
{
<expression>
}.
Subsequently, the function can be called using the
construction:
<result> = <variable>(<arguments>).
Functions
Functions
Literature
1. An Introduction to R
2. Introduction to the R Language: Functions
3. R Tutorial: An R introduction to statistics
4. Kelly Black. R Tutorial

More Related Content

What's hot

2 data types and operators in r
2 data types and operators in r2 data types and operators in r
2 data types and operators in rDr Nisha Arora
 
Postgresql 9.3 overview
Postgresql 9.3 overviewPostgresql 9.3 overview
Postgresql 9.3 overviewAveic
 
Java chapter 6 - Arrays -syntax and use
Java chapter 6 - Arrays -syntax and useJava chapter 6 - Arrays -syntax and use
Java chapter 6 - Arrays -syntax and useMukesh Tekwani
 
Export Data using R Studio
Export Data using R StudioExport Data using R Studio
Export Data using R StudioRupak Roy
 
DDL DATA DEFINATION LANGUAGE
DDL DATA DEFINATION LANGUAGEDDL DATA DEFINATION LANGUAGE
DDL DATA DEFINATION LANGUAGEAbrar ali
 
Import Data using R
Import Data using R Import Data using R
Import Data using R Rupak Roy
 
MarcEdit Shelter-In-Place Webinar 7: Making Regular Expressions work for you ...
MarcEdit Shelter-In-Place Webinar 7: Making Regular Expressions work for you ...MarcEdit Shelter-In-Place Webinar 7: Making Regular Expressions work for you ...
MarcEdit Shelter-In-Place Webinar 7: Making Regular Expressions work for you ...Terry Reese
 
Introduction to Data Structure : Pointer
Introduction to Data Structure : PointerIntroduction to Data Structure : Pointer
Introduction to Data Structure : PointerS P Sajjan
 
2 data structure in R
2 data structure in R2 data structure in R
2 data structure in Rnaroranisha
 
Presentation on c programing satcture
Presentation on c programing satcture Presentation on c programing satcture
Presentation on c programing satcture topu93
 

What's hot (20)

2 data types and operators in r
2 data types and operators in r2 data types and operators in r
2 data types and operators in r
 
R교육1
R교육1R교육1
R교육1
 
C structure and union
C structure and unionC structure and union
C structure and union
 
Postgresql 9.3 overview
Postgresql 9.3 overviewPostgresql 9.3 overview
Postgresql 9.3 overview
 
6. R data structures
6. R data structures6. R data structures
6. R data structures
 
Java chapter 6 - Arrays -syntax and use
Java chapter 6 - Arrays -syntax and useJava chapter 6 - Arrays -syntax and use
Java chapter 6 - Arrays -syntax and use
 
Export Data using R Studio
Export Data using R StudioExport Data using R Studio
Export Data using R Studio
 
Reading Data into R
Reading Data into RReading Data into R
Reading Data into R
 
Arrays in c
Arrays in cArrays in c
Arrays in c
 
DDL DATA DEFINATION LANGUAGE
DDL DATA DEFINATION LANGUAGEDDL DATA DEFINATION LANGUAGE
DDL DATA DEFINATION LANGUAGE
 
Import Data using R
Import Data using R Import Data using R
Import Data using R
 
MarcEdit Shelter-In-Place Webinar 7: Making Regular Expressions work for you ...
MarcEdit Shelter-In-Place Webinar 7: Making Regular Expressions work for you ...MarcEdit Shelter-In-Place Webinar 7: Making Regular Expressions work for you ...
MarcEdit Shelter-In-Place Webinar 7: Making Regular Expressions work for you ...
 
Introduction to Data Structure : Pointer
Introduction to Data Structure : PointerIntroduction to Data Structure : Pointer
Introduction to Data Structure : Pointer
 
2 data structure in R
2 data structure in R2 data structure in R
2 data structure in R
 
Presentation on c programing satcture
Presentation on c programing satcture Presentation on c programing satcture
Presentation on c programing satcture
 
C1320prespost
C1320prespostC1320prespost
C1320prespost
 
Sql fundamentals
Sql fundamentalsSql fundamentals
Sql fundamentals
 
Array in c++
Array in c++Array in c++
Array in c++
 
SQL
SQLSQL
SQL
 
SQL : introduction
SQL : introductionSQL : introduction
SQL : introduction
 

Similar to Files,blocks and functions in R

Similar to Files,blocks and functions in R (20)

R Programming Reference Card
R Programming Reference CardR Programming Reference Card
R Programming Reference Card
 
20170509 rand db_lesugent
20170509 rand db_lesugent20170509 rand db_lesugent
20170509 rand db_lesugent
 
Reference card for R
Reference card for RReference card for R
Reference card for R
 
Short Reference Card for R users.
Short Reference Card for R users.Short Reference Card for R users.
Short Reference Card for R users.
 
R command cheatsheet.pdf
R command cheatsheet.pdfR command cheatsheet.pdf
R command cheatsheet.pdf
 
@ R reference
@ R reference@ R reference
@ R reference
 
R short-refcard
R short-refcardR short-refcard
R short-refcard
 
R reference card
R reference cardR reference card
R reference card
 
R Refcard
R RefcardR Refcard
R Refcard
 
R Basics
R BasicsR Basics
R Basics
 
R language introduction
R language introductionR language introduction
R language introduction
 
Presentation R basic teaching module
Presentation R basic teaching modulePresentation R basic teaching module
Presentation R basic teaching module
 
Statistics lab 1
Statistics lab 1Statistics lab 1
Statistics lab 1
 
R Cheat Sheet – Data Management
R Cheat Sheet – Data ManagementR Cheat Sheet – Data Management
R Cheat Sheet – Data Management
 
Recursion schemes in Scala
Recursion schemes in ScalaRecursion schemes in Scala
Recursion schemes in Scala
 
Introduction to R
Introduction to RIntroduction to R
Introduction to R
 
20130215 Reading data into R
20130215 Reading data into R20130215 Reading data into R
20130215 Reading data into R
 
R programming
R programmingR programming
R programming
 
Data Analysis with R (combined slides)
Data Analysis with R (combined slides)Data Analysis with R (combined slides)
Data Analysis with R (combined slides)
 
Basics of Python programming (part 2)
Basics of Python programming (part 2)Basics of Python programming (part 2)
Basics of Python programming (part 2)
 

More from Vladimir Bakhrushin

Decision-making on assessment of higher education institutions under uncertainty
Decision-making on assessment of higher education institutions under uncertaintyDecision-making on assessment of higher education institutions under uncertainty
Decision-making on assessment of higher education institutions under uncertaintyVladimir Bakhrushin
 
Якими бути стандартам вищої освіти для докторів філософії
Якими бути стандартам вищої освіти для докторів філософіїЯкими бути стандартам вищої освіти для докторів філософії
Якими бути стандартам вищої освіти для докторів філософіїVladimir Bakhrushin
 
Академічна автономія і трансформація української освіти
Академічна автономія і трансформація української освітиАкадемічна автономія і трансформація української освіти
Академічна автономія і трансформація української освітиVladimir Bakhrushin
 
Оптимізація в освіті і управлінні
Оптимізація в освіті і управлінні Оптимізація в освіті і управлінні
Оптимізація в освіті і управлінні Vladimir Bakhrushin
 
Українські університети: Сучасні виклики та можливі відповіді
Українські університети: Сучасні виклики та можливі відповідіУкраїнські університети: Сучасні виклики та можливі відповіді
Українські університети: Сучасні виклики та можливі відповідіVladimir Bakhrushin
 
Два проекти закону україни
Два проекти закону україниДва проекти закону україни
Два проекти закону україниVladimir Bakhrushin
 
Окремі аспекти реформування освіти України з погляду системного підходу
Окремі аспекти реформування освіти України з погляду системного підходуОкремі аспекти реформування освіти України з погляду системного підходу
Окремі аспекти реформування освіти України з погляду системного підходуVladimir Bakhrushin
 
Decision-making in education based on multi-criteria ranking of alternatives
Decision-making in education based on multi-criteria ranking of alternativesDecision-making in education based on multi-criteria ranking of alternatives
Decision-making in education based on multi-criteria ranking of alternativesVladimir Bakhrushin
 
Деякі проблеми прийняття рішень в освіті
Деякі проблеми прийняття рішень в освітіДеякі проблеми прийняття рішень в освіті
Деякі проблеми прийняття рішень в освітіVladimir Bakhrushin
 
Описова статистика в R
Описова статистика в RОписова статистика в R
Описова статистика в RVladimir Bakhrushin
 
Деякі графічні засоби R
Деякі графічні засоби RДеякі графічні засоби R
Деякі графічні засоби RVladimir Bakhrushin
 
Робота з файлами даних в R, блоки виразів, цикли, функції
Робота з файлами даних в R, блоки виразів, цикли, функціїРобота з файлами даних в R, блоки виразів, цикли, функції
Робота з файлами даних в R, блоки виразів, цикли, функціїVladimir Bakhrushin
 
Cluster analysis using k-means method in R
Cluster analysis using k-means method in RCluster analysis using k-means method in R
Cluster analysis using k-means method in RVladimir Bakhrushin
 
Нові застосування статистичних методів в прикладних дослідженнях
Нові застосування статистичних методів в прикладних дослідженняхНові застосування статистичних методів в прикладних дослідженнях
Нові застосування статистичних методів в прикладних дослідженняхVladimir Bakhrushin
 
Парадоксы голосования
Парадоксы голосованияПарадоксы голосования
Парадоксы голосованияVladimir Bakhrushin
 

More from Vladimir Bakhrushin (20)

Decision-making on assessment of higher education institutions under uncertainty
Decision-making on assessment of higher education institutions under uncertaintyDecision-making on assessment of higher education institutions under uncertainty
Decision-making on assessment of higher education institutions under uncertainty
 
Якими бути стандартам вищої освіти для докторів філософії
Якими бути стандартам вищої освіти для докторів філософіїЯкими бути стандартам вищої освіти для докторів філософії
Якими бути стандартам вищої освіти для докторів філософії
 
Академічна автономія і трансформація української освіти
Академічна автономія і трансформація української освітиАкадемічна автономія і трансформація української освіти
Академічна автономія і трансформація української освіти
 
Оптимізація в освіті і управлінні
Оптимізація в освіті і управлінні Оптимізація в освіті і управлінні
Оптимізація в освіті і управлінні
 
Мій 2015
Мій 2015Мій 2015
Мій 2015
 
Українські університети: Сучасні виклики та можливі відповіді
Українські університети: Сучасні виклики та можливі відповідіУкраїнські університети: Сучасні виклики та можливі відповіді
Українські університети: Сучасні виклики та можливі відповіді
 
Два проекти закону україни
Два проекти закону україниДва проекти закону україни
Два проекти закону україни
 
Окремі аспекти реформування освіти України з погляду системного підходу
Окремі аспекти реформування освіти України з погляду системного підходуОкремі аспекти реформування освіти України з погляду системного підходу
Окремі аспекти реформування освіти України з погляду системного підходу
 
Decision-making in education based on multi-criteria ranking of alternatives
Decision-making in education based on multi-criteria ranking of alternativesDecision-making in education based on multi-criteria ranking of alternatives
Decision-making in education based on multi-criteria ranking of alternatives
 
Деякі проблеми прийняття рішень в освіті
Деякі проблеми прийняття рішень в освітіДеякі проблеми прийняття рішень в освіті
Деякі проблеми прийняття рішень в освіті
 
Закон про освіту
Закон про освітуЗакон про освіту
Закон про освіту
 
Описова статистика в R
Описова статистика в RОписова статистика в R
Описова статистика в R
 
Деякі графічні засоби R
Деякі графічні засоби RДеякі графічні засоби R
Деякі графічні засоби R
 
Plot function in R
Plot function in RPlot function in R
Plot function in R
 
Функція plot() в R
Функція plot() в RФункція plot() в R
Функція plot() в R
 
Робота з файлами даних в R, блоки виразів, цикли, функції
Робота з файлами даних в R, блоки виразів, цикли, функціїРобота з файлами даних в R, блоки виразів, цикли, функції
Робота з файлами даних в R, блоки виразів, цикли, функції
 
Cluster analysis using k-means method in R
Cluster analysis using k-means method in RCluster analysis using k-means method in R
Cluster analysis using k-means method in R
 
Нові застосування статистичних методів в прикладних дослідженнях
Нові застосування статистичних методів в прикладних дослідженняхНові застосування статистичних методів в прикладних дослідженнях
Нові застосування статистичних методів в прикладних дослідженнях
 
Парадоксы голосования
Парадоксы голосованияПарадоксы голосования
Парадоксы голосования
 
Starting work with R
Starting work with RStarting work with R
Starting work with R
 

Recently uploaded

_Math 4-Q4 Week 5.pptx Steps in Collecting Data
_Math 4-Q4 Week 5.pptx Steps in Collecting Data_Math 4-Q4 Week 5.pptx Steps in Collecting Data
_Math 4-Q4 Week 5.pptx Steps in Collecting DataJhengPantaleon
 
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptx
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptxSOCIAL AND HISTORICAL CONTEXT - LFTVD.pptx
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptxiammrhaywood
 
Measures of Central Tendency: Mean, Median and Mode
Measures of Central Tendency: Mean, Median and ModeMeasures of Central Tendency: Mean, Median and Mode
Measures of Central Tendency: Mean, Median and ModeThiyagu K
 
Introduction to AI in Higher Education_draft.pptx
Introduction to AI in Higher Education_draft.pptxIntroduction to AI in Higher Education_draft.pptx
Introduction to AI in Higher Education_draft.pptxpboyjonauth
 
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
 
URLs and Routing in the Odoo 17 Website App
URLs and Routing in the Odoo 17 Website AppURLs and Routing in the Odoo 17 Website App
URLs and Routing in the Odoo 17 Website AppCeline George
 
Call Girls in Dwarka Mor Delhi Contact Us 9654467111
Call Girls in Dwarka Mor Delhi Contact Us 9654467111Call Girls in Dwarka Mor Delhi Contact Us 9654467111
Call Girls in Dwarka Mor Delhi Contact Us 9654467111Sapana Sha
 
Contemporary philippine arts from the regions_PPT_Module_12 [Autosaved] (1).pptx
Contemporary philippine arts from the regions_PPT_Module_12 [Autosaved] (1).pptxContemporary philippine arts from the regions_PPT_Module_12 [Autosaved] (1).pptx
Contemporary philippine arts from the regions_PPT_Module_12 [Autosaved] (1).pptxRoyAbrique
 
“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...
“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...
“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...Marc Dusseiller Dusjagr
 
Solving Puzzles Benefits Everyone (English).pptx
Solving Puzzles Benefits Everyone (English).pptxSolving Puzzles Benefits Everyone (English).pptx
Solving Puzzles Benefits Everyone (English).pptxOH TEIK BIN
 
Crayon Activity Handout For the Crayon A
Crayon Activity Handout For the Crayon ACrayon Activity Handout For the Crayon A
Crayon Activity Handout For the Crayon AUnboundStockton
 
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
 
Separation of Lanthanides/ Lanthanides and Actinides
Separation of Lanthanides/ Lanthanides and ActinidesSeparation of Lanthanides/ Lanthanides and Actinides
Separation of Lanthanides/ Lanthanides and ActinidesFatimaKhan178732
 
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...EduSkills OECD
 
Paris 2024 Olympic Geographies - an activity
Paris 2024 Olympic Geographies - an activityParis 2024 Olympic Geographies - an activity
Paris 2024 Olympic Geographies - an activityGeoBlogs
 
The Most Excellent Way | 1 Corinthians 13
The Most Excellent Way | 1 Corinthians 13The Most Excellent Way | 1 Corinthians 13
The Most Excellent Way | 1 Corinthians 13Steve Thomason
 

Recently uploaded (20)

_Math 4-Q4 Week 5.pptx Steps in Collecting Data
_Math 4-Q4 Week 5.pptx Steps in Collecting Data_Math 4-Q4 Week 5.pptx Steps in Collecting Data
_Math 4-Q4 Week 5.pptx Steps in Collecting Data
 
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptx
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptxSOCIAL AND HISTORICAL CONTEXT - LFTVD.pptx
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptx
 
Código Creativo y Arte de Software | Unidad 1
Código Creativo y Arte de Software | Unidad 1Código Creativo y Arte de Software | Unidad 1
Código Creativo y Arte de Software | Unidad 1
 
Measures of Central Tendency: Mean, Median and Mode
Measures of Central Tendency: Mean, Median and ModeMeasures of Central Tendency: Mean, Median and Mode
Measures of Central Tendency: Mean, Median and Mode
 
Introduction to AI in Higher Education_draft.pptx
Introduction to AI in Higher Education_draft.pptxIntroduction to AI in Higher Education_draft.pptx
Introduction to AI in Higher Education_draft.pptx
 
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
 
Staff of Color (SOC) Retention Efforts DDSD
Staff of Color (SOC) Retention Efforts DDSDStaff of Color (SOC) Retention Efforts DDSD
Staff of Color (SOC) Retention Efforts DDSD
 
URLs and Routing in the Odoo 17 Website App
URLs and Routing in the Odoo 17 Website AppURLs and Routing in the Odoo 17 Website App
URLs and Routing in the Odoo 17 Website App
 
TataKelola dan KamSiber Kecerdasan Buatan v022.pdf
TataKelola dan KamSiber Kecerdasan Buatan v022.pdfTataKelola dan KamSiber Kecerdasan Buatan v022.pdf
TataKelola dan KamSiber Kecerdasan Buatan v022.pdf
 
Call Girls in Dwarka Mor Delhi Contact Us 9654467111
Call Girls in Dwarka Mor Delhi Contact Us 9654467111Call Girls in Dwarka Mor Delhi Contact Us 9654467111
Call Girls in Dwarka Mor Delhi Contact Us 9654467111
 
Contemporary philippine arts from the regions_PPT_Module_12 [Autosaved] (1).pptx
Contemporary philippine arts from the regions_PPT_Module_12 [Autosaved] (1).pptxContemporary philippine arts from the regions_PPT_Module_12 [Autosaved] (1).pptx
Contemporary philippine arts from the regions_PPT_Module_12 [Autosaved] (1).pptx
 
“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...
“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...
“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...
 
Solving Puzzles Benefits Everyone (English).pptx
Solving Puzzles Benefits Everyone (English).pptxSolving Puzzles Benefits Everyone (English).pptx
Solving Puzzles Benefits Everyone (English).pptx
 
Crayon Activity Handout For the Crayon A
Crayon Activity Handout For the Crayon ACrayon Activity Handout For the Crayon A
Crayon Activity Handout For the Crayon A
 
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
 
Separation of Lanthanides/ Lanthanides and Actinides
Separation of Lanthanides/ Lanthanides and ActinidesSeparation of Lanthanides/ Lanthanides and Actinides
Separation of Lanthanides/ Lanthanides and Actinides
 
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...
 
Paris 2024 Olympic Geographies - an activity
Paris 2024 Olympic Geographies - an activityParis 2024 Olympic Geographies - an activity
Paris 2024 Olympic Geographies - an activity
 
The Most Excellent Way | 1 Corinthians 13
The Most Excellent Way | 1 Corinthians 13The Most Excellent Way | 1 Corinthians 13
The Most Excellent Way | 1 Corinthians 13
 

Files,blocks and functions in R

  • 1. DATA FILES, BLOCKS OF EXPRESSIONS, CYCLES AND FUNCTIONS IN R Vladimir Bakhrushin, Professor, D.Sc. (Phys. & Math.) Vladimir.Bakhrushin@gmail.com
  • 2. Data reading > data<-read.table(“File name", sep=";", dec=",", header=TRUE, …)  first argument is a reference to the file of *.csv format, that contains data;  argument sep indicates, by which sign the data are separated;  argument dec indicates decimal separator for numbers;  argument header indicates whether the first cells of each column are the column names;  argument row.names indicates whether one of columns contains the row names;  argument nrows specifies the number of lines that need to be read from the table.
  • 4. Writing data to a file write.table(x, file = "", append = FALSE, quote = TRUE, sep = " ", na = "NA", dec = ".", row.names = TRUE, col.names = TRUE, qmethod = c("escape", "double"), …)  x – object that must be written to the file (usually it is a matrix or data table);  file – name of the file to which the data must be written or other connections opened to writing;  append – argument that indicates the need to append data to an existing file or to create a new file with the same name;  quote – indicates the need to take in quotes marks of rows and columns;  na – character set used for the missing values.
  • 5. Writing data to a file write.table(a2, file = "a2.csv", sep = " ", dec = ".")
  • 6. Lists For saving of heterogeneous data in the one object lists can be used. For example: > x1 = c("Milk", "Yogurt", "Sour cream", "Curd") > x2 = c(1, 1, 14, 7) > x3 = c(TRUE, FALSE) > l1 = list(Text = x1, Number = x2, Logic = x3) > l1 To identify specific elements of the list such constructions can be used :  l1$Text[3]; l1$Text;  l1[[1]][2]; l1[[2]].
  • 9. Data editing using function fix()
  • 10. Comments, blocks of expressions Any comment begins with the character #. The test located in the line after this character not regarded as part of the program to be executed. Expressions can be combined into blocks with curly braces. The result of the expressions block is the result of the last of them. > { + x = 9; + y = 4; + x + y; + } [1] 13
  • 11. Conditional constructs “If” – “else” statement is an example of conditional construct: if (<condition>) {<expression_1> }else{ <expression_2>}
  • 12. Loops Loops with predetermined number of iterations can be organized using function “for”: for (<variable> in <expression_1>) <expression_2> If it is need to repeat iterations until a certain condition is fulfilled, we can use a loop “while”: while (<condition>) { <expression> }
  • 13. Loops
  • 14. Loops Infinite loops “Repeat” are used when a procedure should be executed if the interruption condition is not performed. Command “break” is used to interrupt the cycle, and command “next” – to interrupt the current iteration and move to the next one.
  • 15. Functions Function in R is an object, that for a given set of arguments returns a certain value. Usually when the function is declared its value is assigned to some variable. <variabe> = function(<arguments>) { <expression> }. Subsequently, the function can be called using the construction: <result> = <variable>(<arguments>).
  • 18. Literature 1. An Introduction to R 2. Introduction to the R Language: Functions 3. R Tutorial: An R introduction to statistics 4. Kelly Black. R Tutorial