#================================================================================================================#
#========== Jacek Wallusch ==========#
#========== R: SOME HELPFUL HINTS ==========#
#================================================================================================================#
#----- SEQUENCE OF NUMBERS -----
# use seq-function to generate a sequence of numbers
from_1_to_2 <- seq(from = 1, # starting value
to = 2, # end value
by = 0.1) # define the increment of the sequence
from_1_to_2
# populating a vector by using rep-function
my_sincere_request <- rep("PLEASE ASK QUESTIONS if you don't understand something", # element to be replicated
5) # specify the number times
my_sincere_request
# replicating elements of a vector
Scottish_Star_in_Rocknrolla <- rep(c(1, 2),
5)
# rep-function can be used to replicate vectors or factors
his_name <- rep(c("Gerard Butler"), 5)
#----- GENERATING VECTORS AND MATRICES -----
# create 3 variables each generated as N~(1,0.5) and T = 50:
var01 <- rnorm(50, mean = 1, sd = 0.5)
var02 <- rnorm(50, mean = 1, sd = 0.5)
var03 <- rnorm(50, mean = 1, sd = 0.5)
# round the generated variables to the 3rd decimal place:
round(var01,3)
round(var02,3)
round(var03,3)
# stack the variables (i.e. save them as a vector):
vec01 <- c(var01, var02, var03)
vec01
# save the variables as matrix
# use the vector vec01 (ncol = 3 specifies the number of columns)
mat01 <- matrix(data = vec01, ncol = 3)
mat01
# or save directly the vars
mat02 <- matrix(data = c(var01, var02, var03), ncol = 3)
# if you want to extract the second column of matrix mat02 (recall the matrix notation, e.g. [22,2] means 22nd row 2nd column)
sec_col_mat02 <- mat02[,2]
# if you want to extract the second row of matrix mat02
sec_row_mat02 <- mat02[2,]
#----- BASIC OPERATIONS -----
# MULTIPLICATION
product_of_variables <- var01 * var02 * var03
# ADDITION
sum_of_variables <- var01 + var02 + var03
# check the result:
check_sum <- var01[1] + var02[1] + var03[1]
sum_of_variables[1]
check_sum
#----- IFELSE-Function -----
# use ifelse-function to check if the sums are equal, run lines 42-45 and check the result in the console below
are_the_sums_equal <- ifelse(sum_of_variables[1] == check_sum, # this is the problem to be checked (== is a logical operator, for more visit: http://www.statmethods.net/management/operators.html)
"Indeed, the sums are equal", # this is what is reported if the problem is correctly specified (i.e. if the sums are EXACTLY equal)
"No, the sums are not equal") # this is what is reported if the problem is not correctly specified
are_the_sums_equal
# yet another example (this time the alternative (or 'no' in R-))
inequality_to_check <- ifelse(sum(var01) <= 0,
"The sum is not larger than 0",
"The sum is larger than 0")
inequality_to_check