MIS 207

R Basic Syntax


I. Ozkan, PhD

Professor
MIS
Cankaya University

iozkan@cankaya.edu.tr

Fall 2025

Quick Refresher from Previous Classes

✅ Why Programming

✅ Why

RStudio IDE

❌ Basic

❌ Data Types in

RStudio Again

Working Directory

Manual Folder Creation and Planning

RStudio Project Creation (For the Curious )

RStudio Create New Project

RStudio Create New Project

RStudio New Project Opened

RStudio Project Options

RStudio Project Options


For More Details please visit RStudio User Guide, Project section https://docs.posit.co/ide/user/ide/guide/code/projects.html

R Basic Syntax: R prompt

Default R prompt is >

Can be changed with options() function

options(prompt="R> ")  
options(prompt="> ")  

R Basic Syntax: “Continuation: +”

“+” is continuation for incomplete line

library(tidyverse)
dat <- tibble(names = c("smile","school","office","blush","smirk","heart_eyes"),
              emoji = map_chr(names, emo::ji)) %>% 
  tibble::rowid_to_column("n")

R Basic Syntax: “Comment #”

All of the text, values, assignments etc. will be interpreted as comment after # symbol

x = 3#5
x
[1] 3
x = #35
Error: attempt to use zero-length variable name
# x = 35

nothing happens

R Basic Syntax: Assignment

Recommended

x <- 3  

or (?)

x = 3  
x <- 3 # recommended  
x      # Retrieval
## [1] 3
x = 5 # not recommended 
x      # Retrieval 
## [1] 5
7 -> x # not recommended
x      # Retrieval
## [1] 7

R Basic Syntax: Retrieval

x   
[1] 3
X  
Error: object ‘X’ not found

R Basic Syntax: Built in Objects

T 
## [1] TRUE
F 
## [1] FALSE
pi
## [1] 3.141593
exp(1) # Euler's number, or e, is a mathematical constant  
## [1] 2.718282

R Basic Syntax: Spaces

3 + 5  
## [1] 8
4  +  9 
## [1] 13
x <- 7+8 # not recommended
x <- 7 + 8 # recommended
x <- 7  +  8 # not recommended

What happens here?

x < - 5 + 3
## [1] FALSE

R as Calculator: Operators: Basic Calculations

1 + 1 # addition 
## [1] 2
45 - 25 # subtraction
## [1] 20
2 * 5 # multiplication   
## [1] 10
10 / 5 # division 
## [1] 2
2^3 # to the power  
## [1] 8
8^(1/3) # to the power  
## [1] 2
4^0.5 # to the power  
## [1] 2
11%%3  # mod 
## [1] 2
11%/%3  # integer division 
## [1] 3

Scientific Notation: e

1e3
## [1] 1000
2.1e2
## [1] 210

R as Calculator: Order of Operations

From highest to lowest

+ Parentheses: (, )
+ Exponents: ^ or **
+ Multiply: *
+ Divide: /
+ Add: +
+ Subtract: -
# * and - 
12*5-30
## [1] 30
20-100*2
## [1] -180
# * and / 
12*5/30
## [1] 2
5/30*12
## [1] 2
20*100/2
## [1] 1000
# (), *, /, + 
(3+5)*4-5*6
## [1] 2
4*(25-20)/10
## [1] 2
(4+(5*(2^2))) # hard to read
## [1] 24
4+5*2^2     # clear, if you remember the rules
## [1] 24
4+5*(2^2)    # if you forget some rules, this might help
## [1] 24
# very small numbers  
4/100000 # [1] 4e-05 means 4x10^(-5)
## [1] 4e-05
12e3  # 12x10^3  
## [1] 12000

R as Calculator

10/0
## [1] Inf
-10/0
## [1] -Inf
-10/0 + 1/0
## [1] NaN

R as Calculator: Comparisons

Logical operators are operators that return TRUE and FALSE values

Comparisons
Operator Description
< less than
<= less than or equal to
> greater than
>= greater than or equal to
== exactly equal to
!= not equal to
Results: Are Logical, TRUE and FALSE
# Equality  
1==1 # == read as "is equal to"  
## [1] TRUE
# Inequality  
1!=1 # != read as "is not equal to"  
## [1] FALSE
1!=2
## [1] TRUE
12345 != 3425 
## [1] TRUE
# greater than or equal to
1 >= 1  
## [1] TRUE
1 >= -2
## [1] TRUE
12345 >= 3425 
## [1] TRUE
# less than or equal to
1 <= 1  
## [1] TRUE
1 <= 2
## [1] TRUE
12345 <= 3425 
## [1] FALSE
# less than 
12345 < 3425 
## [1] FALSE
# greater than 
12345 > 3425 
## [1] TRUE
# if there is a match or not
12345 %in% c(3425, 12, 12345) 
## [1] TRUE

R as Calculator: Logical Operators

Logical Operators
Operator Description
!x logical negation, (NOT)
x & y elementwise logical AND
x && y logical AND (left to right)
x | y elementwise logical OR
x || y logical OR (left to right)
xor(x,y) elementwise exclusive OR
isTRUE(x) as name suggested
isFALSE(x) as name suggested
&&, ||: appropriate for programming control-flow

R as Calculator: More About TRUE and FALSE

TRUE + TRUE # = ? 
TRUE + FALSE # = ?
TRUE - TRUE # = ?
!TRUE # = ?
!FALSE # = ?
TRUE & FALSE # = ?  
TRUE | FALSE # = ? 
TRUE * FALSE # = ? 
TRUE == TRUE # = ? 
TRUE == 1 # = ? 
TRUE == 0 # = ? 
TRUE == -1 # = ?
FALSE == 0 # = ? 
FALSE == -1 # = ?
FALSE == 0.5 # = ?

R as Calculator: More About TRUE and FALSE

TRUE + TRUE 
## [1] 2
TRUE + FALSE 
## [1] 1
TRUE - TRUE 
## [1] 0
!TRUE 
## [1] FALSE
!FALSE
## [1] TRUE
TRUE & FALSE 
## [1] FALSE
TRUE | FALSE
## [1] TRUE
TRUE * FALSE
## [1] 0
TRUE == TRUE 
## [1] TRUE
TRUE == 1 
## [1] TRUE
TRUE == 0 
## [1] FALSE
TRUE == -1 
## [1] FALSE
FALSE == 0 
## [1] TRUE
FALSE == -1
## [1] FALSE
FALSE == 0.5
## [1] FALSE

R as a calculator: Mathematical Functions

trigonometric functions

sin(1)  
## [1] 0.841471
sin(pi)  
## [1] 1.224606e-16
sin(pi/2)  
## [1] 1
cos(1)
## [1] 0.5403023
cos(pi)
## [1] -1
cos(pi/2)
## [1] 6.123032e-17
tan(1)
## [1] 1.557408
tan(pi)
## [1] -1.224647e-16
tan(pi/2)
## [1] 1.633124e+16
atan2(1, 1)
## [1] 0.7853982
tan(atan2(1, 1))
## [1] 1
atan(2/1) == atan2(2,1)
## [1] TRUE
tan(atan(8/4)) # slope of line passing through (x=0,0) and (x=4,8)
## [1] 2

R as a calculator: Mathematical Functions

Logarithms and Exponential

# natural logarithm
log(1)  
## [1] 0
log(exp(1))  # see exp(1) :)
## [1] 1
# to base 10 
log10(10)
## [1] 1
log10(0.1)
## [1] -1
# to base 2 
log2(2^5)
## [1] 5
log2(1/2^5)
## [1] -5
log(-0.5) # Not a Number, NaN
## [1] NaN
log2(-0.5) # Not a Number, NaN
## [1] NaN
log10(-0.5) # Not a Number, NaN  
## [1] NaN
log(0) # -Inf 
## [1] -Inf
# Exponential 
exp(-Inf)
## [1] 0
exp(0)
## [1] 1
exp(1)
## [1] 2.718282
exp(sin(1))
## [1] 2.319777

R as as a calculator: Precision

Computers may represent decimal numbers with a certain degree of precision. Two numbers which look the same when printed out by R, may actually have different underlying representations and therefore be different by a small margin of error (called Machine numeric tolerance). If numbers are not integers, use all.equal function

pi 
## [1] 3.141593
all.equal(3.141593,pi)
## [1] "Mean relative difference: 1.102658e-07"
all.equal(1.234,1.234)
## [1] TRUE
all.equal(1.234,1.2345)
## [1] "Mean relative difference: 0.0004051864"

Variables

Note: Recall <- or -> are assignment operators

x <- 1/10  

1/5 -> y

x 
## [1] 0.1
y
## [1] 0.2
x >= y  
## [1] FALSE
all.equal(x,y)
## [1] "Mean relative difference: 1"
# type: will see later 
class(x) 
## [1] "numeric"
typeof(x)
## [1] "double"
x + y  
## [1] 0.3
x * y  
## [1] 0.02
x / y 
## [1] 0.5
x^y
## [1] 0.6309573
z=10
z
## [1] 10
z^2
## [1] 100
z*x/y
## [1] 5

Vectorization Teaser

: is Colon operator; from:to in steps of 1 or -1

c(): Combine Values into a Vector

# Basic  
1:10
##  [1]  1  2  3  4  5  6  7  8  9 10
17:25 
## [1] 17 18 19 20 21 22 23 24 25
pi:6 # real number 
## [1] 3.141593 4.141593 5.141593
6:pi # integer number 
## [1] 6 5 4
2^(1:5) # element-wise 
## [1]  2  4  8 16 32
x <- 5

x^(3:5)  
## [1]  125  625 3125
y <- 1:5 

2^y  
## [1]  2  4  8 16 32
x^y
## [1]    5   25  125  625 3125
y^x
## [1]    1   32  243 1024 3125
(1:3)^(2:4)
## [1]  1  8 81
(1:3)^(2:7) # shorter recycled :)
## [1]    1    8   81    1   64 2187
z <- 2:4
z
## [1] 2 3 4
y
## [1] 1 2 3 4 5
y^z # observe warning  
## [1]   1   8  81  16 125
l <- c(1,3,7,10)
l
## [1]  1  3  7 10
lstr <- c("one","two","three")
lstr
## [1] "one"   "two"   "three"
lstr2 <- c(lstr,2) # observe 2
lstr2 
## [1] "one"   "two"   "three" "2"
lstr3 <- c(lstr,l) # observe numeric values
lstr3
## [1] "one"   "two"   "three" "1"     "3"     "7"     "10"
rbind(l,c(2,4,6,8)) # creates a 2-d data, 2 by 4  
##   [,1] [,2] [,3] [,4]
## l    1    3    7   10
##      2    4    6    8
rbind(l,2,4,6,8) # creates a 2-d data, 5 by 4  
##   [,1] [,2] [,3] [,4]
## l    1    3    7   10
##      2    2    2    2
##      4    4    4    4
##      6    6    6    6
##      8    8    8    8

Combining Number, Logical and Character: Teaser

TRUE:4 # what happens to TRUE
## [1] 1 2 3 4
T:4 # same 
## [1] 1 2 3 4
4:FALSE
## [1] 4 3 2 1 0
F:4
## [1] 0 1 2 3 4
c(T,T,F,T)
## [1]  TRUE  TRUE FALSE  TRUE
c(T,4,F,T) # observe 
## [1] 1 4 0 1
c("Ali", "Veli", "Hatice")
## [1] "Ali"    "Veli"   "Hatice"
c("Ali", "Veli", "Hatice", TRUE)
## [1] "Ali"    "Veli"   "Hatice" "TRUE"
c("Ali", "Veli", "Hatice", TRUE, 4)
## [1] "Ali"    "Veli"   "Hatice" "TRUE"   "4"

Environment

ls()
##  [1] "Description" "l"           "l_table_1"   "l_table_2"   "lstr"       
##  [6] "lstr2"       "lstr3"       "Operator"    "x"           "y"          
## [11] "z"
ls(all.names=TRUE)
##  [1] ".Random.seed" "Description"  "l"            "l_table_1"    "l_table_2"   
##  [6] "lstr"         "lstr2"        "lstr3"        "Operator"     "x"           
## [11] "y"            "z"
ls # a function is an object in R :)  
## function (name, pos = -1L, envir = as.environment(pos), all.names = FALSE, 
##     pattern, sorted = TRUE) 
## {
##     if (!missing(name)) {
##         pos <- tryCatch(name, error = function(e) e)
##         if (inherits(pos, "error")) {
##             name <- substitute(name)
##             if (!is.character(name)) 
##                 name <- deparse(name)
##             warning(gettextf("%s converted to character string", 
##                 sQuote(name)), domain = NA)
##             pos <- name
##         }
##     }
##     all.names <- .Internal(ls(envir, all.names, sorted))
##     if (!missing(pattern)) {
##         if ((ll <- length(grep("[", pattern, fixed = TRUE))) && 
##             ll != length(grep("]", pattern, fixed = TRUE))) {
##             if (pattern == "[") {
##                 pattern <- "\\["
##                 warning("replaced regular expression pattern '[' by  '\\\\['")
##             }
##             else if (length(grep("[^\\\\]\\[<-", pattern))) {
##                 pattern <- sub("\\[<-", "\\\\\\[<-", pattern)
##                 warning("replaced '[<-' by '\\\\[<-' in regular expression pattern")
##             }
##         }
##         grep(pattern, all.names, value = TRUE)
##     }
##     else all.names
## }
## <bytecode: 0x000001972cc9fdc8>
## <environment: namespace:base>
rm(x) # remove x

rm(z) # remove z

rm(list=ls()) # Remove all (do not use assignment "<-" here) 

Packages

.libPaths()
## [1] "C:/Users/CANKAYA/AppData/Local/R/win-library/4.5"
## [2] "C:/Program Files/R/R-4.5.1/library"
.Library
## [1] "C:/PROGRA~1/R/R-45~1.1/library"

Package Installation

Some important functions for package installation and call:

# installing a package 
install.packages("ggplot2") 

# installing more than one package  
pkgs <- c("ggplot2","gapminder","dplyr")
install.packages(pkgs) 

library(ggplot2)
detach("package:ggplot2")

require(ggplot2)

Package Installation

 install.packages(pkgs, lib, repos = getOption("repos"),
                 contriburl = contrib.url(repos, type),
                 method, available = NULL, destdir = NULL,
                 dependencies = NA, type = getOption("pkgType"),
                 configure.args = getOption("configure.args"),
                 configure.vars = getOption("configure.vars"),
                 clean = FALSE, Ncpus = getOption("Ncpus", 1L),
                 verbose = getOption("verbose"),
                 libs_only = FALSE, INSTALL_opts, quiet = FALSE,
                 keep_outputs = FALSE, ...)
                 

Detach Packages

detach(name, pos = 2L, unload = FALSE, character.only = FALSE,
       force = FALSE)
library(ggplot2)
detach(package:ggplot2)

Imprtant Packages to Install

Help

lm {stats}  R Documentation
Fitting Linear Models
Description
lm is used to fit linear models, including multivariate ones. It can be used to carry out regression, single stratum analysis of variance and analysis of covariance (although aov may provide a more convenient interface for these).

Usage
lm(formula, data, subset, weights, na.action,
   method = "qr", model = TRUE, x = FALSE, y = FALSE, qr = TRUE,
   singular.ok = TRUE, contrasts = NULL, offset, ...)
Arithmetic {base}   R Documentation
Arithmetic Operators
Description
These unary and binary operators perform arithmetic on numeric or complex vectors (or objects which can be coerced to them).

Usage
+ x
- x
x + y
x - y
x * y
x / y
x ^ y
x %% y
x %/% y
Arguments

Other Resources