1. Data Types

R has three basic data types.

  • numbers are called numerics

  • text is called characters

  • booleans are called logicals

There are also other data types that will not be discussed.

  • integers

  • complex numbers

  • raw data (bytes)

Note the use of the binding operator <- which binds values to a variable.

1.1. Numerics

Numerics are the usual numbers that you may apply addition, subtraction, multiplication, division and modulo operators to.

[1]:
a <- 10
b <- 2

c <- a + b
d <- a - b
e <- a * b
f <- a / b
g <- a %% b
[2]:
print(c)
[1] 12
[3]:
print(d)
[1] 8
[4]:
print(e)
[1] 20
[5]:
print(f)
[1] 5
[6]:
print(g)
[1] 0

1.2. Special values

  • NA represents missing values

  • Inf represents positive infinity

  • -Inf represents negative infinity

  • NaN represents not a number

  • NULL represents no value

1.3. Characters

Characters are just text data.

[7]:
a <- 'Hello, world!'
print(a)
[1] "Hello, world!"

To check the type of a.

[8]:
typeof(a)
'character'

To get the length of a.

[9]:
nchar(a)
13

1.3.1. String concatenation

Concatenating strings is accomplished through paste.

[10]:
a <- 'Hello, '
b <- 'world!'
c <- paste(a, b)
print(c)
[1] "Hello,  world!"

1.3.2. String substitution

To substitute a string for another, use gsub.

[11]:
a <- 'Hello, world!'
b <- gsub('world', 'earth', a)
print(b)
[1] "Hello, earth!"

1.3.3. Substring detection

To detect if a substring exists within a string use the grepl function.

[12]:
a <- 'Hello, world!'
[13]:
grepl('world', a)
TRUE
[14]:
grepl('earth', a)
FALSE

1.4. Logicals

Logicals are just True and False.

[15]:
a <- TRUE
b <- FALSE
c <- as.logical('TRUE')
d <- as.logical('FALSE')
[16]:
print(a)
[1] TRUE
[17]:
print(b)
[1] FALSE
[18]:
print(c)
[1] TRUE
[19]:
print(d)
[1] FALSE