简体   繁体   中英

Replacement has more rows than data in for loop

First, I do realize that there is a question with a similar title, but it didn't seem to solve my problem.

I am simply trying to build a logarithmic stock price index with log base 10 with a for loop like this:

t <- nrow[dat]

dat$logind <- matrix(NA, t, 1)
dat$logind[1] <- 100

for (i in 2:t) {
  dat$logind[i] <- (dat$logind[i-1] * (1+dat$logr[i])) 
}

dat is the dataframe, logind is just a column that I created to hold the index, and logr has the logarithmic returns. However, this throws me the following:

Error in `$<-.data.frame`(`*tmp*`, "logind", value = c(100, 99.3891882,  : 
  replacement has 1155 rows, data has 1154

I read that this error could be solved with using another way to select the column like dat[,column] but how do I use this when I already have [i] there? Or if you have another solution to this problem. Thanks.

I think you meant t <- nrow(dat) instead of t <- nrow[dat] . Using t as variable name can be dangerous because you're overwriting function t (matrix/vector transpose).

You can get rid of your for loop by using R vectorized operators, like this:

dat$longind <- c(100, dat$logind[1:(nrow(dat)-1)] * (1+dat$logr[-1])) )

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM