处理R中的NA和NAN

时间:2015-01-18 15:31:36

标签: r na

我正在尝试为下面的代码运行100,000个实例的简单模拟。当试图得到dlogP的sd和平均值时,我收到sd(dlogP):NA和mean(dlogP):NaN。我相信我应该得到一个类似于5%的原始rnorm的sd偏差。有人可以帮助我,因为我做错了吗?我试图调整似乎有效的迭代次数,但我需要生成100,000个实例。提前谢谢。

set.seed(2013)
P_1 <- 100               # Initial price of stock
r <- rnorm(100000, .01, .05) # Generating 100,000 instances
P <- P_1*cumprod(1+r)        
set.seed(2013)
logP<- log(P)
dlogP <-log1p(P)-logP    # The change in logs from t+1 and t
dlogP 
head(dlogP,1)            # Will output the first value of the matrix
sd(dlogP)
mean(dlogP)
plot(P)

1 个答案:

答案 0 :(得分:3)

如果您坚持每日1%的回报率,则可以按日志比例进行,而不会触及Inf

set.seed(2013)
P_1 <- 100               # Initial price of stock
r <- rnorm(100000, .01, .05) # Generating 100,000 instances 
logP <- log(P_1) + cumsum(log(1+r))
dlogP <-diff(logP)    # The change in logs from t+1 and t
#dlogP 
head(dlogP,1)            # Will output the first value of the matrix
sd(dlogP)
mean(dlogP)