撰寫函式

R 金融中級

Lore Dirick

Manager of Data Science Curriculum at Flatiron School

函式結構

func_name <- function(arguments) {
  body
}
R 金融中級

加一

add_one <- function(x) {
  x_plus_one <- x + 1
  return(x_plus_one)
}

add_one(7)
8
add_one <- function(x) {
  x + 1
}

add_one(7)
8
R 金融中級

使用選用引數

add <- function(x, value = 1) {
  x + value
}

add(7)
8
add(7, value = 3)
10
R 金融中級

計算算術報酬

第 4 章影片 2 投影片.027.png

prices <- c(23.4, 23.8, 22.3)

# S_(t) - S(t-1) 向量 diff(prices)
0.4 -1.5
# S_(t-1) 向量
prices[-length(prices)]
23.4 23.8
# 算術報酬
diff(prices) / prices[-length(prices)]
0.01709402 -0.06302521
R 金融中級

計算算術報酬

prices <- c(23.4, 23.8, 22.3)

arith_returns <- function(x) { diff(x) / x[-length(x)] }
arith_returns(prices)
0.01709402 -0.06302521
R 金融中級

一起來練習吧!

R 金融中級

Preparing Video For Download...