如何使代码更简单并在表中打印

时间:2017-06-04 09:43:20

标签: r

我正在为n = 1,2,5,10,100,500和1000计算几个值,并且不确定如何在更简单的代码中执行此操作。我为每一个编写了n = 1,2,5,..,1000的代码,并想知道是否有一种方法编写代码而不重复它?

dt <- T/n1 
T <- 1
sigma <- 0.2
S0 <- 100
K1 <- 1
r <- 0.05
p <- (exp(r*dt)-d)/(u-d)
u <- exp(sigma*(dt)^0.5)
d <- exp(-sigma*(dt)^0.5)
e <- exp(-r*T)
c1 <- gamma(1+n1)/(gamma(1+K1)*gamma(1+(n1-K1)))

##n = 1

n1 <- 1

for(i in 0:n1)
{
calculate1 <- c1*p^i*(1-p)^(n1-i)*(u^(i)*d^(n1-i)*S0-K1)
}

price1 <- e*calculate1
print(price1)

##n = 2
dt <- T/n2 
T <- 1
sigma <- 0.2
S0 <- 100
K2 <- 2
r <- 0.05
p <- (exp(r*dt)-d)/(u-d)
u <- exp(sigma*(dt)^0.5)
d <- exp(-sigma*(dt)^0.5)
e <- exp(-r*T)
c1 <- gamma(1+n2)/(gamma(1+K2)*gamma(1+(n2-K2)))
n2 <- 2

for(i in 0:n2)
{
  calculate2 <- c1*p^i*(1-p)^(n2-i)*(u^(i)*d^(n2-i)*S0-K2)
}

price2 <- e*calculate2
print(price2)

## I do the same thing for n=5,10,100,500 and 1000


pricesintable <- matrix(c(price1,price2,price5,price10, price100, price500,   price1000), ncol =1, byrow = TRUE)
colnames(pricesintable) <- c("Price")
rownames(pricesintable) <- c("1","2","5","10","100","500","1000")
pricesintable <- as.table(pricesintable)
print(pricesintable)

如何制作更简单的代码?

0 个答案:

没有答案