R from week 2

Tips

To insert code chunk in R notebook try Ctrl + Alt + I
To insert <- we can use Alt + - Add a new chunk by clicking the Insert Chunk button on the toolbar or by pressing Ctrl+Alt+I.

When you save the notebook, an HTML file containing the code and output will be saved alongside it (click the Preview button or press Ctrl+Shift+K to preview the HTML file).

The preview shows you a rendered HTML copy of the contents of the editor. Consequently, unlike Knit, Preview does not run any R code chunks. Instead, the output of the chunk when it was last run in the editor is displayed. ## Function In this case dot is a part of the variable’s name

say.hello <- function(){
  return(print('hello world'))
}
say.hello()
## [1] "hello world"

add argument/input for the function also we can set the default argument

say.something <- function(somethingWhat="hello world"){
  return(print(somethingWhat))
}
say.something()
## [1] "hello world"
say.something('hello chucmap')
## [1] "hello chucmap"

Conditionals

So we have traditional if…else statement

isChucMapBeo <- function(weight){
  if(weight > 65)
    print('chuc qua map')
  else if(weight <= 65 & weight > 40)
    print('chuc van okay')
  else
    print('de nghi em chuc an them')
}
isChucMapBeo(75)
## [1] "chuc qua map"
isChucMapBeo(50)
## [1] "chuc van okay"
isChucMapBeo(20)
## [1] "de nghi em chuc an them"

Beside if…else, we have ifelse which is oneline of code for conditionals

# For 1 value
ifelse(1==1,"helya","nooooo")
## [1] "helya"
# For a vector
x <- c(1,3,1,3,4,56,2,324,0,1)
ifelse(x==1,"True","FALSE")
##  [1] "True"  "FALSE" "True"  "FALSE" "FALSE" "FALSE" "FALSE" "FALSE" "FALSE"
## [10] "True"
ifelse(x==1, x*5, x*0)
##  [1] 5 0 5 0 0 0 0 0 0 5

Compound Tests

This is very interesting in R, it starts with is. is.numeric() or is.na()
We also have logical operator & && for and and | || for or
- Double form compare only one element from each side, while the single form
compare each element of each side - Single form: mostly left side is checked

a <- c(1, 1, 0, 1)
b <- c(2, 1, 0, 1)
ifelse(a == 1 & b == 1, "Yes", "No")
## [1] "No"  "Yes" "No"  "Yes"
ifelse(a == 1 && b == 1, "Yes", "No")
## [1] "No"
if(1==1 && 4==1)
  print('is checked')
if(1==1 || 3==2)
  print('is checked with ||')
## [1] "is checked with ||"

Switch

#basic switch, based on position
switch(3, 
       "Learn",
       "R Programming",
       "Tutorial",
       "Gateway"
)
## [1] "Tutorial"
#More advanced switch, based on value
 
number1 <- 30
number2 <- 20
#operator <- readline(prompt="Please enter any ARITHMETIC OPERATOR You wish!: ")
operator <- "%%"
 
switch(operator,
       "+" = print(paste("Addition of two numbers is: ", number1 + number2)),
       "-" = print(paste("Subtraction of two numbers is: ", number1 - number2)),
       "*" = print(paste("Multiplication of two numbers is: ", number1 * number2)),
       "^" = print(paste("Exponent of two numbers is: ", number1 ^ number2)),
       "/" = print(paste("Division of two numbers is: ", number1 / number2)),
       "%/%" = print(paste("Integer Division of two numbers is: ", number1 %/% number2)),
       "%%" = print(paste("Modular of two numbers is: ", number1 %% number2))
)
## [1] "Modular of two numbers is:  10"

Loop

for (i in 1:5){
  print(i)
}
## [1] 1
## [1] 2
## [1] 3
## [1] 4
## [1] 5
phrase <- "Good night,"
for(word in c('Good morning', 'and', 'good afternoon')){
  phrase <- paste(phrase, word)
  print(phrase)
}
## [1] "Good night, Good morning"
## [1] "Good night, Good morning and"
## [1] "Good night, Good morning and good afternoon"
paste('hello', 'word') # paste will add a space in between
## [1] "hello word"

Another example

fake.data <- matrix(rnorm(500), ncol=5) # create fake 100 x 5 data set
head(fake.data,2) # print first two rows
##           [,1]      [,2]       [,3]      [,4]      [,5]
## [1,] 0.6620137  1.139640 -0.3350994 2.2942554 0.5845661
## [2,] 0.5621076 -1.305136  0.6869938 0.5288692 1.1177722
col.sums <- numeric(ncol(fake.data)) # variable to store running column sums
for(i in 1:nrow(fake.data)) {
  col.sums <- col.sums + fake.data[i,] # add ith observation to the sum
}
col.sums
## [1]   5.518255  -3.813436   3.671316 -14.674434  -8.688702
colSums(fake.data)
## [1]   5.518255  -3.813436   3.671316 -14.674434  -8.688702

while loops

day <- 1
num.days <- 365
while(day <= num.days) {
  day <- day + 1
}

repeat loop

x <- 1
repeat {
    print(x)
    x = x+1
    if (x == 4){
        break
    }
}
## [1] 1
## [1] 2
## [1] 3

Various apply() function

apply(object that working on, region to apply(1=rows,2=cols), function

# build the matrix
(theMatrix <- matrix(1:9, nrow=3))
##      [,1] [,2] [,3]
## [1,]    1    4    7
## [2,]    2    5    8
## [3,]    3    6    9
# sum the row
apply(theMatrix, 1, sum)
## [1] 12 15 18
# sum the col
apply(theMatrix, 2, sum)
## [1]  6 15 24
#ignore the NAs
apply(theMatrix, 1, sum, na.rm=TRUE)
## [1] 12 15 18