R 很难通过循环而不是逐个使用插补值填充NAs

R 很难通过循环而不是逐个使用插补值填充NAs,r,matrix,R,Matrix,所以我在R中有一个矩阵,它是一个数据帧的子集,只包含一个ID、分组变量和一系列1100个读数。我希望最终通过一个程序来运行这些读数,该程序需要均匀的值间距-但是每一行(大约100行)每天都有两到三个“缺失值”,我们因为各种原因干扰了传感器。我只想对这些值进行黄土插补——一般来说,这些值占每行的3-5%,不多了,所以我不太担心这几个值的影响,只担心它们丢失了 下面是我使用的代码。请原谅我在使用回路进行提升时的任何不雅行为,我认识到yval对于我所做的事情来说并不是完全必要的,但它使跟踪变得更容易

所以我在R中有一个矩阵,它是一个数据帧的子集,只包含一个ID、分组变量和一系列1100个读数。我希望最终通过一个程序来运行这些读数,该程序需要均匀的值间距-但是每一行(大约100行)每天都有两到三个“缺失值”,我们因为各种原因干扰了传感器。我只想对这些值进行黄土插补——一般来说,这些值占每行的3-5%,不多了,所以我不太担心这几个值的影响,只担心它们丢失了

下面是我使用的代码。请原谅我在使用回路进行提升时的任何不雅行为,我认识到yval对于我所做的事情来说并不是完全必要的,但它使跟踪变得更容易

#Take out the matrix for LOESS imputation
df3mat <- as.matrix(cccsdf3[,c(3:1102)])
#Generate a list of the time values for the LOESS generation
timelist <- c(1:timevals)
#Use LOESS imputation to fill values for each row in the df3mat matrix.

for (i in nrow(df3mat)){
  #Take each row at a time into the yval vector
  yval <- df3mat[i,]
  #Get a vector of which values in yval are missing
  MissingList <- which(is.na(yval))  

  #Use span=0.13 for the LOESS curve, which comes out to about 1 day of information in the window for fitting the curve
  yval.loess <- loess(y ~ x, span=0.13, data.frame(x=timelist, y=yval))
  #Get a set of predictions just for the missing values
  yval.missing <-  predict(yval.loess, data.frame(x=MissingList))

  #Replace the missing values in yval with the yval.missing objects as imputed via LOESS
  yval[is.na(yval)] <- yval.missing

  #And set the row in df3mat to the now filled yval vector.
  df3mat[i,] <- yval

}
#取出黄土插补矩阵

df3mat您需要修复
for
循环。错误在这里:

for(i in nrow(df3mat)) {
    .....
}
nrow(df3mat)
只是一个标量值(单个值)-不是可以循环的。你想要的是:

for(i in 1:nrow(df3mat)) {
    .....
}


如果您提供一些示例输入数据来解决您的问题,这将有所帮助。哦,谢谢!我真不敢相信我错过了。当然,这是一个不会出现在运行特定线路上的部分!
for(i in seq_len(nrow(df3mat))) {
    .....
}