简体   繁体   English

在R中替换矩阵中的NA

[英]Replacing NAs in a Matrix in R

I have created a container of NAs and am trying to replace the NAs with a specified value that is an argument in one of the functions. 我创建了NA的容器,并试图用指定的值替换NA,该值是函数之一中的自变量。

num.cars.beg<-20
num.cars.end<-70
num.cars.incr<-5
num.cols<-(abs(num.cars.end-num.cars.beg)/num.cars.incr)+1
num.its<-10
car.var.mat<-matrix(NA,num.its,num.cols) #creates empty container to hold 
results
car.intervals<-c(seq(num.cars.beg,num.cars.end, num.cars.incr))
colnames(car.var.mat)<-paste(car.intervals,"Cars",sep = " ")
rownames(car.var.mat)<-paste("Iter.",c(seq(1,num.its,1)),sep = "")

This has created a matrix where the rows are driven by "num.its" and the columns are "num.cars" from 20-70 in intervals of 5. For each iteration, I would like to run each column through my formula "run.sim" and replace the NAs with the value of run.sim. 这创建了一个矩阵,其中行由“ num.its”驱动,列是“ num.cars”,范围为20-70,间隔为5。对于每次迭代,我想通过公式“ run”运行每一列.sim”,并用run.sim的值替换NA。 So for example: 因此,例如:

               num.cars = 20     num.cars = 25
num.its = 1   run.sim1 output    run.sim2 output
num.its = 2   run.sim3 output    run.sim4 output

where, 哪里,

run.sim(num.cars = each value in car.intervals, num.its = 2)

The key to filling in the container is 1) to make sure the for loop structured as "1:numcols" or "1:numrows" and 2) that the argument in run.sim for num.cars is defined through [] of the matrix car.intervals, so that you clarify that the function loops through each row i, its respective location in each column j. 填充容器的关键是1)确保for循环的结构为“ 1:numcols”或“ 1:numrows”,以及2)通过的[]定义run.sim中num.cars的参数。矩阵car.intervals,以便您清楚该函数遍历每行i,其在每列j中的位置。

num.its <- 1
num.itr <- 10
for (i in 1:num.itr){
  for (j in 1:num.cols){
    car.var.mat[i,j]<-mean(run.sim(
     num.cars = car.intervals[j], 
     num.its = num.its))
  }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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