简体   繁体   中英

Assigning value to Matrix in R

I have loaded a data set using read.csv. This contains headers in the first row and then a bunch of stock prices in different columns.

I am then trying to perform a rolling analysis (mean, SD or any other simple statistical function and assign it an an element in a matrix that I have defined)

However I keep getting NA for all the cells when I am writing to csv

My Code

{
APD = read.table(file="C:\\Path\\Pasted Data Temp.csv",head=TRUE,sep=",",blank.lines.skip = TRUE,row.names = NULL);
DMA = matrix(nrow=dim(APD)[1]+25,ncol=dim(APD)[2]+25)
a = ncol(APD);
DMAno = 20; 
for(i in 3:a) {
z = length(APD[1])
for(j in DMAno:z)
    {
    DMA[[i][j]] <- mean(APD$ABNL[j-DMAno+2:j])
    }
}
}

As agstudy suggested rollapply is probably the best option, since it will be extremely faster.

As for your code: you need some brackets in (j-DMAno+2):j and in R one subsets matrix in somewhat different manner, namely i-th column and j-th row of DMA is accesed via DMA[j,i] . data.frame$x[] produces some redundant subseting. Try this one:

for(i in 3:a) {
  z = length(APD[1])
  for(j in DMAno:z)
      {
      DMA[j,i] <- mean(APD[(j-DMAno+2):j,"ABNL"])
      }
  }
}

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