Menulis fungsi

R Tingkat Menengah untuk Keuangan

Lore Dirick

Manager of Data Science Curriculum at Flatiron School

Struktur fungsi

func_name <- function(arguments) {
  body
}
R Tingkat Menengah untuk Keuangan

Tambah satu

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 Tingkat Menengah untuk Keuangan

Menggunakan argumen opsional

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

add(7)
8
add(7, value = 3)
10
R Tingkat Menengah untuk Keuangan

Menghitung return aritmetika

Menghitung return aritmetika

prices <- c(23.4, 23.8, 22.3)

# vektor S_(t) - S(t-1) diff(prices)
0.4 -1.5
# vektor S_(t-1)
prices[-length(prices)]
23.4 23.8
# Return aritmetika
diff(prices) / prices[-length(prices)]
0.01709402 -0.06302521
R Tingkat Menengah untuk Keuangan

Menghitung return aritmetika

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 Tingkat Menengah untuk Keuangan

Ayo berlatih!

R Tingkat Menengah untuk Keuangan

Preparing Video For Download...