## 1.1 How to use R
# Q1.1.2
# Order of calculations is as you would expect and brackets work as you are used to
## Variables
# Q1.1.4 The program outputs 1, which is the value of x
# Q1.1.5
x+5
x*5
x*5+x
# all of these work you would assume
# Q1.1.6
y <- 5*20
# y only saves the output of the calculation, not how we got there
# Q1.1.7
z <- x+y
# Q1.1.8
# does not save changed value:
z+10
#saves changed value:
z <- z+10
## Functions
a <- sum(1,2,3)
# Q1.1.10 function is 'sum', argument is 1,2,3, and output (6) is saved in variable a
# Q1.1.11 The output is exactly as one would expect
# Q1.1.12
# getwd() finds your current working directory (wd)
## 1.2. Simple data types
## Numbers ("numeric")
# Q1.2.1
typeof(x) # double
typeof(5.1) # double
typeof(pi) # double
typeof(2L) # integer, the large L indicates that R should interpret this as integer and not double
## Characters (text)
# Q 1.2.2
typeof('abc') # character
# Q1.2.3
# we cannot do addition on numeric value and character, they are not compatible
## Logical (Boolean, i.e. TRUE or FALSE)
#
# Q1.2.4
x < 10
y == 20
## Vectors
#
# Q1.2.5
# output is
# 1 2 3 4 5 6 7 8 9 10
# and it is type integer (which is the type of the elements in the vector)
# Q1.2.6
# vector1 and vector2 are not the same.
# the argument by tells seq how large jumps it should make between numbers
# the argument length tells seq how long the resulting vector should be
# Q1.2.7
vector3 <- seq(40,100,by=10)
# Q1.2.8
charactervector <- c('a','b','c')
## Vector indexing
# Q1.2.9
vector3[2]
# returns 50
# Q1.2.10
# you can use :
vector1[1:2]
# or you can use c()
vector1[c(1,2)]
# Q1.2.11
# running this returns the values from vector1 which are TRUE in the logical vector
# Q1.2.12
# this returns a logical vector stating for which of the elements the logical operation is true and false
# if we wanted to get the relevant values, we could run
vector1[vector1>10]
# Q1.2.13
vector3[vector3>50 & vector3<80]
## 1.3 Loops
# Q1.3.2
# we only need to change the years on the first line (the header)
for(i in 2020:2025){
print(paste0("Is this year ",i,"?"))
}
# Q1.3.3
# before the loop we initialise a variable with 0
currvalue <- 0
for(j in 1:100){
# the next line takes whatever currvalue has at that iteration and adds j, and saves these as currvalue for next iteration
currvalue <- currvalue + j
}
# print out the final value
currvalue
# double check that our result is correct
sum(1:100)
# it is! yay!
# 1.4 Packages
# Q1.4.1
install.packages('psych')
# Q1.4.2
library(psych)
# Q1.4.3
describe(vector1)
Created by Juulia Suvilehto
juulia.suvilehto@iki.fi
This work is licensed under a Creative Commons Attribution-NonCommercial-ShareAlike 4.0 International License