简体   繁体   English

在 R 中使用循环函数计算错误

[英]Calculate Errors using loop function in R

I have two data matrices both having the same dimensions.我有两个数据矩阵都具有相同的维度。 I want to extract the same series of columns vectors.我想提取相同系列的列向量。 Then take both series as vectors, then calculate different errors for example mean absolute error (mae) , mean percentage error (mape) and root means square error然后将两个系列作为向量,然后计算不同的误差,例如平均绝对误差(mae) 、平均百分比误差(mape)和均方根误差
(rmse) . (均方根) My data matrix is quite large dimensional so I try to explain with an example and calculate these errors manually as:我的数据矩阵是非常大的维度,所以我尝试用一​​个例子来解释并手动计算这些错误:

mat1<- matrix(6:75,ncol=10,byrow=T) 
mat2<- matrix(30:99,ncol=10,byrow=T) 
mat1_seri1 <- as.vector(mat1[,c(1+(0:4)*2)])
mat1_seri2<- as.vector(mat1[,c(2+(0:4)*2)])
mat2_seri1 <- as.vector(mat1[,c(1+(0:4)*2)])
mat2_seri2<- as.vector(mat1[,c(2+(0:4)*2)])
mae1<-mean(abs(mat1_seri1-mat2_seri1))
mae2<-mean(abs(mat1_seri2-mat2_seri2))
For mape 
mape1<- mean(abs(mat1_seri1-mat2_seri1)/mat1_seri1)*100
mape2<- mean(abs(mat1_seri2-mat2_seri2)/mat1_seri2)*100

similarly, I calculate rmse from their formula, as I have large data matrices so manually it is quite time-consuming.同样,我根据他们的公式计算rmse ,因为我有大量数据矩阵,因此手动操作非常耗时。 Is it's possible to do this using looping which gives an output of the errors (mae,mape,rmse) term for each series separately.是否可以使用循环来执行此操作,该循环分别为每个系列提供错误(mae、mape、rmse)项的输出。

I'm not sure if this is what you are looking for, but here is a function that could automate the process, maybe there is also a better way:我不确定这是否是您要查找的内容,但这里有一个可以自动化该过程的功能,也许还有更好的方法:

fn <- function(m1, m2) {
  stopifnot(dim(m1) == dim(m2))
  
  mat1_seri1 <- as.vector(m1[, (1:ncol(m1))[(1:ncol(m1))%%2 != 0]])
  mat1_seri2 <- as.vector(m1[, (1:ncol(m1))[!(1:ncol(m1))%%2]])
  mat2_seri1 <- as.vector(m2[, (1:ncol(m2))[(1:ncol(m2))%%2 != 0]])
  mat2_seri2 <- as.vector(m2[, (1:ncol(m2))[!(1:ncol(m2))%%2]])
  
  mae1 <- mean(abs(mat1_seri1-mat2_seri1))
  mae2 <- mean(abs(mat1_seri2-mat2_seri2))
  
  mape1 <- mean(abs(mat1_seri1-mat2_seri1)/mat1_seri1)*100
  mape2 <- mean(abs(mat1_seri2-mat2_seri2)/mat1_seri2)*100
  
  setNames(as.data.frame(matrix(c(mae1, mae2, mape1, mape2), ncol = 4)), 
           c("mae1", "mae2", "mape1", "mape2"))
}

fn(mat1, mat2)

  mae1 mae2    mape1    mape2
1   24   24 92.62581 86.89572

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

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