환웅 데이터

[R 프로그래밍] Functions 본문

R 프로그래밍

[R 프로그래밍] Functions

환 웅 2025. 3. 11. 11:00

 

Data Frame: 행과 열을 갖는 2차원의 표 형태로 데이터를 저장하는 것을 데이터프레임이라고 합니다. 변수 역할을 하는 column과, 관측값을 나열하는 row로 이루어져있습니다.

객체
특성
차원
Scalar
1개의 값이 저장
0차원
Vector
1가지 데이터 타입(유형)만을 저장 (Atomic vector)
1차원
Dataframe
2가지 이상 데이터타입의 열(변수)과 행(관측값)의 형태로 값을 저장할 수 있음
2차원
Matrix
df과 달리 모든 값의 데이터타입이 동일해야함 
2차원

 


Practice 1 (Week4 Function Exercises)

In the second part of the book we have talked about the Future Value (FV), and we have extensively used its simplest version of the FV formula. Let’s now consider the “opposite” value: the Present Value which is the current value of a future sum of money or stream of cash flows given a specified rate of return.

Consider the simplest version of the formula to calculate the Present Value given by:

PV = FV / (1 + r)^n
  • PV = present value (the initial deposit)
  • FV = future value (how much you’ll have)
  •  r = rate of return (e.g. annual rate of return)
  • n  = number of periods (e.g. number of years)

Write a function present_value() to compute the Present Value based on the above formula.

Answer:

present_value = function(fv, r, n) {
  pv = fv / (1 + r)^n
  return(pv)
}

 

Practice 2 (Week4 Function Exercises)

Write another function to compute the Future Value, but this time the output should be a list with two elements:


1. vector year from 0 to provided year

2. vector amount from amount at year 0, till amount at the provided year

For example, something like this:

fv_list(present = 1000, rate = 0.02, year = 3)

Answer:

fv_list = function(present, rate, year) {
  amount = present * (1 + rate)^(0:year)
  fv = list(0:year, amount)
  names(fv) <- c("years", "amount")
  fv
}

fv_list(1000, 0.02, 3)

 

 

Practice 3 (Week4 Function Exercises)

Write another function to compute the Future Value, but this time the output should be a “table” with two columns: year and amount. For example, something like this:

fv_table(present = 1000, rate = 0.02, year = 3)

You can use either a matrix or a data.frame.

 

Answer:

fv_df = function(present, rate, year) {
  fv = present * (1 + rate)^(0:year)
  data.frame(year = 0:year, amount = fv)
}

fv_matrix = function(present, rate, year) {
  amount = present * (1 + rate)^(0:year)
  fvm = matrix(c(0:year, amount), nrow = 4, byrow = F)
  colnames(fvm) = c("years", "amount")
  fvm
}

fv_df(1000, 0.02, 3)
fv_matrix(1000, 0.02, 3)

Works Cited:

https://m.blog.naver.com/regenesis90/222188967067

 

[R] 데이터프레임(data.frame) (1) 기초 및 예제 : 데이터프레임의 정의, 데이터프레임 만들기 · 편집

1. 데이터프레임(Data Frame)의 개념과 생성 방법 1) 데이터프레임의 개념 행과 열을 갖는 2차원 표의 형...

blog.naver.com

 


환웅, Minor in Data Science & B.A. in Statistics at University of California, Berkeley

 

'R 프로그래밍' 카테고리의 다른 글

Overfitting  (0) 2022.12.07
Evaluating and Improving and Predictions  (0) 2022.12.07