Difference between revisions of "RPR-Syntax basics"

From "A B C"
Jump to navigation Jump to search
m
m
Line 28: Line 28:
 
== Abstract ==
 
== Abstract ==
 
<section begin=abstract />
 
<section begin=abstract />
<!-- included from "../components/RPR-Syntax_basics.components.wtxt", section: "abstract" -->
+
<!-- included from "./components/RPR-Syntax_basics.components.txt", section: "abstract" -->
 
This unit discusses simple R commands and basic syntax, operators, and R objects (variables).
 
This unit discusses simple R commands and basic syntax, operators, and R objects (variables).
 
<section end=abstract />
 
<section end=abstract />
Line 37: Line 37:
 
== This unit ... ==
 
== This unit ... ==
 
=== Prerequisites ===
 
=== Prerequisites ===
<!-- included from "../components/RPR-Syntax_basics.components.wtxt", section: "prerequisites" -->
+
<!-- included from "./components/RPR-Syntax_basics.components.txt", section: "prerequisites" -->
<!-- included from "ABC-unit_components.wtxt", section: "notes-prerequisites" -->
+
<!-- included from "./data/ABC-unit_components.txt", section: "notes-prerequisites" -->
 
You need to complete the following units before beginning this one:
 
You need to complete the following units before beginning this one:
*[[RPR-Console]]
+
*[[RPR-Console|RPR-Console (Console and scripts)]]
*[[RPR-Help]]
+
*[[RPR-Help|RPR-Help (Getting help for R)]]
*[[RPR-Installation]]
+
*[[RPR-Installation|RPR-Installation (Installing R and RStudio)]]
*[[RPR-Setup]]
+
*[[RPR-Setup|RPR-Setup (Setup R to work with it)]]
  
 
{{Vspace}}
 
{{Vspace}}
Line 49: Line 49:
  
 
=== Objectives ===
 
=== Objectives ===
<!-- included from "../components/RPR-Syntax_basics.components.wtxt", section: "objectives" -->
+
<!-- included from "./components/RPR-Syntax_basics.components.txt", section: "objectives" -->
 
This unit will ...
 
This unit will ...
 
* ... introduce basic operations of R syntax;
 
* ... introduce basic operations of R syntax;
Line 59: Line 59:
  
 
=== Outcomes ===
 
=== Outcomes ===
<!-- included from "../components/RPR-Syntax_basics.components.wtxt", section: "outcomes" -->
+
<!-- included from "./components/RPR-Syntax_basics.components.txt", section: "outcomes" -->
 
After working through this unit you ...
 
After working through this unit you ...
 
* ... can evaluate R expressions by tyoing them on the console;
 
* ... can evaluate R expressions by tyoing them on the console;
Line 69: Line 69:
  
 
=== Deliverables ===
 
=== Deliverables ===
<!-- included from "../components/RPR-Syntax_basics.components.wtxt", section: "deliverables" -->
+
<!-- included from "./components/RPR-Syntax_basics.components.txt", section: "deliverables" -->
<!-- included from "ABC-unit_components.wtxt", section: "deliverables-time_management" -->
+
<!-- included from "./data/ABC-unit_components.txt", section: "deliverables-time_management" -->
 
*<b>Time management</b>: Before you begin, estimate how long it will take you to complete this unit. Then, record in your course journal: the number of hours you estimated, the number of hours you worked on the unit, and the amount of time that passed between start and completion of this unit.
 
*<b>Time management</b>: Before you begin, estimate how long it will take you to complete this unit. Then, record in your course journal: the number of hours you estimated, the number of hours you worked on the unit, and the amount of time that passed between start and completion of this unit.
<!-- included from "ABC-unit_components.wtxt", section: "deliverables-journal" -->
+
<!-- included from "./data/ABC-unit_components.txt", section: "deliverables-journal" -->
 
*<b>Journal</b>: Document your progress in your [[FND-Journal|Course Journal]]. Some tasks may ask you to include specific items in your journal. Don't overlook these.
 
*<b>Journal</b>: Document your progress in your [[FND-Journal|Course Journal]]. Some tasks may ask you to include specific items in your journal. Don't overlook these.
<!-- included from "ABC-unit_components.wtxt", section: "deliverables-insights" -->
+
<!-- included from "./data/ABC-unit_components.txt", section: "deliverables-insights" -->
 
*<b>Insights</b>: If you find something particularly noteworthy about this unit, make a note in your [[ABC-Insights|'''insights!''' page]].
 
*<b>Insights</b>: If you find something particularly noteworthy about this unit, make a note in your [[ABC-Insights|'''insights!''' page]].
 
{{Vspace}}
 
 
 
=== Evaluation ===
 
<!-- included from "../components/RPR-Syntax_basics.components.wtxt", section: "evaluation" -->
 
<!-- included from "ABC-unit_components.wtxt", section: "eval-none" -->
 
<b>Evaluation: NA</b><br />
 
:This unit is not evaluated for course marks.
 
  
 
{{Vspace}}
 
{{Vspace}}
Line 92: Line 83:
 
<div id="BIO">
 
<div id="BIO">
 
== Contents ==
 
== Contents ==
<!-- included from "../components/RPR-Syntax_basics.components.wtxt", section: "contents" -->
+
<!-- included from "./components/RPR-Syntax_basics.components.txt", section: "contents" -->
  
 
==Simple commands==
 
==Simple commands==
Line 253: Line 244:
  
 
== Notes ==
 
== Notes ==
<!-- included from "../components/RPR-Syntax_basics.components.wtxt", section: "notes" -->
+
<!-- included from "./components/RPR-Syntax_basics.components.txt", section: "notes" -->
<!-- included from "ABC-unit_components.wtxt", section: "notes" -->
+
<!-- included from "./data/ABC-unit_components.txt", section: "notes" -->
 
<references />
 
<references />
  
Line 263: Line 254:
 
<div id="ABC-unit-framework">
 
<div id="ABC-unit-framework">
 
== Self-evaluation ==
 
== Self-evaluation ==
<!-- included from "../components/RPR-Syntax_basics.components.wtxt", section: "self-evaluation" -->
+
<!-- included from "./components/RPR-Syntax_basics.components.txt", section: "self-evaluation" -->
 
<!--
 
<!--
 
=== Question 1===
 
=== Question 1===
Line 288: Line 279:
  
  
<!-- included from "ABC-unit_components.wtxt", section: "ABC-unit_ask" -->
+
<!-- included from "./data/ABC-unit_components.txt", section: "ABC-unit_ask" -->
  
 
----
 
----
Line 316: Line 307:
 
</div>
 
</div>
 
[[Category:ABC-units]]
 
[[Category:ABC-units]]
<!-- included from "ABC-unit_components.wtxt", section: "ABC-unit_footer" -->
+
<!-- included from "./data/ABC-unit_components.txt", section: "ABC-unit_footer" -->
  
 
{{CC-BY}}
 
{{CC-BY}}

Revision as of 01:27, 6 January 2018

Basics of R syntax


 

Keywords:  Simple commands and basic syntax, operators, variables, class, mode, and attributes


 



 


 


Abstract

This unit discusses simple R commands and basic syntax, operators, and R objects (variables).


 


This unit ...

Prerequisites

You need to complete the following units before beginning this one:


 


Objectives

This unit will ...

  • ... introduce basic operations of R syntax;
  • ... provide examples for use of operators;
  • ... discuss variable names.


 


Outcomes

After working through this unit you ...

  • ... can evaluate R expressions by tyoing them on the console;
  • ... know how to write and debug complex R expressions using lots of parentheses;
  • ... are able to avoid common issues when choosing variable names.


 


Deliverables

  • Time management: Before you begin, estimate how long it will take you to complete this unit. Then, record in your course journal: the number of hours you estimated, the number of hours you worked on the unit, and the amount of time that passed between start and completion of this unit.
  • Journal: Document your progress in your Course Journal. Some tasks may ask you to include specific items in your journal. Don't overlook these.
  • Insights: If you find something particularly noteworthy about this unit, make a note in your insights! page.


 


Contents

Simple commands

The R command line evaluates expressions. Expressions can contain constants, variables, operators and functions of the various datatypes that R recognizes.


 

Operators

The common arithmetic operators are recognized in the usual way.

Task:
OPen an RStudio session and try the following operators on numbers:

5
5 + 3
5 + 1 / 2 # Think first is this 3 or 5.5
3 * 2 + 1
3 * (2 + 1)
2^3 # Exponentiation
8 ^ (1/3) # Third root via exponentiation
7 %% 2  # Modulo operation (remainder of integer division)
7 %/% 2 # Integer division

# Logical operators return TRUE or FALSE
#    Unary:
TRUE
FALSE
! TRUE  # read carefully: the "!" - "not" - is easily overlooked
! FALSE

#    Binary

1 == 2
1 != 2
1 < 2
1 > 2

1 > 1
1 >= 1
1 < 1
1 <= 1

#    & AND
TRUE & TRUE
TRUE & FALSE
FALSE & FALSE

#    | OR
TRUE | TRUE
TRUE | FALSE
FALSE | FALSE

# Predict what this will return
!(FALSE | (! FALSE))


Task:

Practice
Given the expression shown below, the value of lastNum is 9:
numbers <- c(16, 20, 3, 5, 9)
lastNum <- tail(numbers, 1)    # explain what this does

Write R expressions:

1) To check whether lastNum is less than 6 or greater than 10

2) To check whether lastNum is in the interval [10, 20). (By the rules of mathematical notation this means 10 is included but 20 is not).

3) To output TRUE if the following operation gives 2:

  • take lastNum
  • divide it by 7
  • subtract the integer part and the first digit after the decimal point (hint: multiply by 10, then integer division by 1 gives you ... what)
  • multiply by 100
  • integer divide by 1
  • take the third root

(Hints: use lots of parentheses and compare the final result to 2. To debug, select parts of the code and execute separately. If the console gets stuck because it is expecting a closing parenthesis, and all you see is the "+" sign, simply press <escape> to abort evaluation.)

Check your answers (but don't cheat) ...

1) lastNum < 6 | lastNum > 10
2) lastNum >= 10 & lastNum < 20
3) ((((9/7) - ((((9/7) * 10) %/% 1 )/10)) * 100) %/% 1 )^(1/3) == 2


 

Variables

In order to store the results of expressions and computations, you can freely assign them to variables[1]. Variables are created by R whenever you first use them (i.e. space in memory is allocated to the variable and a value is stored in that space.) Variable names distinguish between upper case and lower case letters. There are a small number of reserved names that you are not allowed to redefine, and R syntax contains very small number of predefined constants, such as pi. However these constants can be overwritten - be careful: R will allow you to define pi <- 3 but casually redefining the foundations of mathematics may lead to unintended consequences. Read more about variable names at:

?make.names
?reserved

To assign a value to a constant, use the assignment operator <-. This is the default way of assigning values in R. You could also use the = sign, but there are subtle differences. (See: ?"<-"). There is a variant of the assignment operator <<- which is sometimes used inside functions. It assigns to a global context. This is possible, but not preferred since it generates a side effect of a function. Don't do this. Forget about <<- again.

a <- 5
a
a + 3
b <- 8
b
a + b
a == b # not assignment: equality test
a != b # not equal
a < b  # less than

Note that all of R's data types (as well as functions and other objects) can be assigned to variables.

There are very few syntactic restrictions on variable names (discussed eg. here) but this does not mean esoteric names are good. For the sake of your sanity, use names that express the meaning of the variable, and that are unique. Many R developers use dotted.variable.names, some people use the pothole_style, my personal preference is to write camelCaseNames. And while the single letters c f n s Q are syntactically valid variable names, they coincide with commands for the debugger browser and will execute debugger commands, rather than displaying variable values when you are debugging. Finally, try not to use variable names that are the same as parameter names in functions. Alas, you see this often in code, but such code can be hard to read because the semantics of the actual argument versus the parameter name becomes obscured. It's just common sense really: don't call different things by the same name.

# I don't like...
col <- c("red", "grey")
hist(rnorm(200), col=col)

# I prefer instead something like...
rgStripes <- c("red", "grey")
hist(rnorm(200), col=rgStripes)


 



 


Further reading, links and resources

 


Notes

  1. We call these "variables" because of what function they perform in our code, the actually are R "objects".


 


Self-evaluation

 



 




 

If in doubt, ask! If anything about this learning unit is not clear to you, do not proceed blindly but ask for clarification. Post your question on the course mailing list: others are likely to have similar problems. Or send an email to your instructor.



 

About ...
 
Author:

Boris Steipe <boris.steipe@utoronto.ca>

Created:

2017-08-05

Modified:

2017-09-10

Version:

1.0

Version history:

  • 1.0 Completed to first live version
  • 0.1 Material collected from previous tutorial

CreativeCommonsBy.png This copyrighted material is licensed under a Creative Commons Attribution 4.0 International License. Follow the link to learn more.