R as a calculator

Use R to add 1 and 1

# do the math here
1+1
## [1] 2

assigning things to variables

So there’s the assignment operator <- which assigns a variable a value. Like so:

# assigning the variable
z <- 3
# printing the variable to the screen
z
## [1] 3

make a variable called ee, and assign the value of 4.3, and print it out

# do it here
ee <- 4.3
ee
## [1] 4.3

vectors

in R, vectors are strings of values, like: 2, 4, 1. You can make vectors with the c() function, like this:

# making the vector
example.vec <- c(2, 4, 1)
# printing it out to the screen
example.vec
## [1] 2 4 1

make a vector called practice.vec, and assign it to 8, 6, 7, 5, 3, 0, 9, and then print it out

# do it here
practice.vec <- c(8, 6, 7, 5, 3, 0, 9)
practice.vec
## [1] 8 6 7 5 3 0 9

tip: you can make sequences with a colon between numbers. Like this:

1:6
## [1] 1 2 3 4 5 6
6:3
## [1] 6 5 4 3

so that’s cool

vector math

so a cool thing is that you can add vectors together:

# making some vectors
a.vec <- c(2,4)
b.vec <- c(6,0)

a.vec + b.vec
## [1] 8 4

Recycling

..and then there’s something called recyling…

# making a longer vec
c.vec <- 1:6

a.vec + c.vec
## [1]  3  6  5  8  7 10

What happened?

a.vec added to c.vec by adding 2 then 4 and repeating this sequence until it added to each number of the six number sequence c.vec

also, that was when the lengths were multiples of each other.

d.vec <- 1:3

a.vec + d.vec
## Warning in a.vec + d.vec: longer object length is not a multiple of shorter
## object length
## [1] 3 6 5

What happened?

Error because the small number was not a multiple of the larger number, so it couldn’t add the way it did on the previous one

concatenating vectors

just like putting numbers together to make a vector, you can use the c() function

c(a.vec, b.vec)
## [1] 2 4 6 0
# and you can store that somewhere
cat.vec <- c(a.vec, b.vec)
cat.vec
## [1] 2 4 6 0

concatenate c.vec and d.vec

# do it here
c(c.vec, d.vec)
## [1] 1 2 3 4 5 6 1 2 3

indexing vectors

what if you want certain things from a vector? Like the 2nd element?

you can use the

Types of variables

you can use the class() function to determine the type of variables

# making some vectors
num.vec <- 1
char.vec <- "a"
log.vec <- TRUE
fac.vec <- as.factor("OhNo")

What are their types?

class(num.vec)
## [1] "numeric"
class(char.vec)
## [1] "character"
class(log.vec)
## [1] "logical"
class(fac.vec)
## [1] "factor"

neat.