Liz's Blog

就是要學R #7:R programming 基礎篇

| Comments

看影片聽英文解釋,跟著一起操作反而比較理解,但是要用中文解釋定義,反而有點難,還是去看影片學習比較好。

Udemy
課程名稱:Data Science and Machine Learning Bootcamp with R
講師:Jose Portilla

1.Logical Operator(練習&、 |、!,分別代表並且、或及不是)

x <- 32
x > 25 & x < 40 & x == 32                   #TRUE
x == 30 | x <10                             #FALSE
!(x==32)                                    #FALSE
df <- ToothGrowth
head(df)

df[df$dose >= 1,]
subset(df,dose>1)

df[df$dose >= 1 & df$supp == "VC",]
subset(df,dose > 1 & df$supp == "VC") 
tf <- c(T,F)
tt <- c(T,T)
ft <- c(F,T)

tt & tf                # TRUE FALSE
tt | ft                # TRUE TRUE
ft && tt               # FALSE 只比第一個
tt || tf               # TRUE 只比第一個

2.if, else, else if
(1)if
使用規則:

  if (條件式) {
     #執行XXX
  }
raining <- TRUE
raining_percentage <- 70

if (raining_percentage < 60){
  raining <- FALSE
}
print(raining)

(2)if & else
使用規則:

  if (條件式) {
     #執行XXX
  } else {
     #執行XXX
  }
raining_percentage <- 70

if (raining_percentage < 30){
  print("It is sunshine day")
} else {
  print("Don't forget to bring umbrella")
}

(3)if & else if & else
使用規則:

  if (條件式) {
     #執行XXX
  } else if
     #執行XXX
  } else {
     #執行XXX
  }
raining_percentage <- 70

if (raining_percentage <= 30){
  print("It is sunshine day")
} else if (raining_percentage <= 60) {
  print("Maybe bring umbrella is better")
} else {
  print("Umbrella saves you")
}

3.while loops(如果特定條件成立,系統會持續做某事)
(1)使用規則:

  while (條件式) {
     #執行XXX
  }
x <- 0

while(x<5){
  cat('x is currently:',x)
  print('x is still less than 5, adding 1 to x')
  
  x <- x+1
}

(2)加上if再試試看

x <- 0

while(x < 5){
    
    cat('x is currently: ',x)
    print(' x is still less than 10, adding 1 to x')
    
    # add one to x
    x <- x+1
    if(x==5){
        print("x is equal to 5! Terminating loop")
    }
}

(3)使用break停止特定條件,以下面例子就是break之後的print("I will also print, woohoo!")不會出現了。

x <- 0

while(x < 5){
    
    cat('x is currently: ',x)
    print(' x is still less than 5, adding 1 to x')
    
    # add one to x
    x <- x+1
    if(x==5){
        print("x is equal to 5!")
        break
        print("I will also print, woohoo!")
    }
}

4.for loops
使用規則:

  for (temp_var in object){
    #在某段迴圈,執行XXX
  }

(1)如果在vector中,有兩種方法可以做:

vec <- c(1,2,3)
for (temp_var in vec){
  print(temp_var)
}
vec <- c(1,2,3)
for (i in 1:length(vec)){
  print(vec[i])
}

(2)list的用法和vector差不多,只是要注意print的時候,li[[i]]要雙括號。

li <- list(1,2,3)
for (temp_var in li){
  print(temp_var)
}
li <- list(1,2,3)
for (i in 1:length(li)){
    print(li[[i]])
}

(3)matrix

mat <- matrix(1:6, nrow=3)
mat

for (num in mat){
  print(num)
}

(4)for loop巢狀結構運用(下面這個例子是先印出第一橫排的所有數字,接著才接著第二橫排,以此類推)

mat <- matrix(1:6, nrow=3)
mat

for (row in 1:nrow(mat)){
    for (col in 1:ncol(mat)){
        print(paste('The element at row:',row,'and col:',col,'is',mat[row,col]))
    }
}

5.Function
(1)沒有input的function()

greeting <- function(){
  print('Hello!')
}
greeting() 

(2)可以依照input來改變輸出結果

greeting <- function(name){
  print(paste('Hello',name))
}
greeting('Susan')
add_num <- function(num1,num2){
    print(num1+num2)
}
add_num(1,5)

(3)預設name的輸出為Guest

greeting <- function(name='Guest'){
    print(paste('Hello ',name))
}

greeting()                     #在沒有輸入的情況下,會出現預設結果

greeting('Susun')              #有輸入則會覆蓋預設

(4)使用return而非print的話,可以把結果指定為變數。

greeting <- function(name='Guest',title='大大'){
  return(paste(name,' ',title))
}

greeting()
greeting('Susan')

var <- greeting('Susan','Mrs')
var

(5)scope會讓變數只存在限定function內,而非整段程式中。

twice <- function(input) {
  result <- input * 2 
  return(result)
}

twice(4)             #輸入result或input都會出現找不到物件

但如果不包含在function中則沒有這樣的限制。

v <- "I'm global v"
stuff <- "I'm global stuff"

fun <- function(stuff){
    print(v) 
    stuff <- 'Reassign stuff inside func'
    print(stuff)
}

print(v) 
print(stuff) 
fun(stuff)                        #會接受argument stuff,先印出v,然後啟動'Reassign stuff inside func'

簡單來說,就是要看變數是放在function內還是外。

test <- function(b) {
  b <- 5*b
  b
}
var <- 2
double(var)
var

Comments

comments powered by Disqus