编写函数

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

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 金融中级

Passons à la pratique !

R 金融中级

Preparing Video For Download...