approxfun 的矩阵应用,用于更快的线性插值
Matrix application of approxfun for faster linear interpolation
我有一个测量日期值的数据框,我需要在一个大矩阵中为新日期创建 prediction/interpolation。目前,我正在使用 approxfun()
创建一个新的插值函数,然后我对矩阵中的每一行使用 apply()
。问题是,我的矩阵很大,apply()
和 approxfun()
很慢。我将在优化例程中使用它,所以速度是一个问题。此外,apply()
命令的结果也需要进行转换。有没有更好的方法可以在不使用 apply()
或类似方法的情况下对每一行新数据进行插值预测?我还有原始日期范围之外的新数据,所以 approxfun()
会处理这个问题,但也许还有其他选择?
library(microbenchmark)
# input data
Date <- c(2015, 2014.5, 2014, 2013.5, 2013, 2012.5, 2012, 2011.5, 2011)
CFC11 <- c(227.346, 228.718, 230.202, 231.419, 232.786, 234.177, 235.506, 236.463, 237.423)
Input <- data.frame(Date, CFC11)
# New Dates
Well1 <- c(2015.6, 2014.2, 2013.1)
Well2 <- c(2013.7, 2011.9, 2010)
NDates <- rbind(Well1, Well2)
NDates <- matrix(NDates, nrow = 2, ncol = 3)
# Input function
CFC11fun <- approxfun(Input$Date,Input$CFC11,rule=2)
# Apply the input function to the dates to get the input at the new dates
# rowwise
# this transposes the result, so I would need to transpose it back
t(apply(NDates,1,CFC11fun))
# looks at timing
microbenchmark(t(apply(NDates,1,CFC11fun)), times = 1000, unit = "us")
只需在整个矩阵上调用您的函数,并将结果整形为相同维度的矩阵:
matrix(CFC11fun(NDates), nrow=nrow(NDates))
我有一个测量日期值的数据框,我需要在一个大矩阵中为新日期创建 prediction/interpolation。目前,我正在使用 approxfun()
创建一个新的插值函数,然后我对矩阵中的每一行使用 apply()
。问题是,我的矩阵很大,apply()
和 approxfun()
很慢。我将在优化例程中使用它,所以速度是一个问题。此外,apply()
命令的结果也需要进行转换。有没有更好的方法可以在不使用 apply()
或类似方法的情况下对每一行新数据进行插值预测?我还有原始日期范围之外的新数据,所以 approxfun()
会处理这个问题,但也许还有其他选择?
library(microbenchmark)
# input data
Date <- c(2015, 2014.5, 2014, 2013.5, 2013, 2012.5, 2012, 2011.5, 2011)
CFC11 <- c(227.346, 228.718, 230.202, 231.419, 232.786, 234.177, 235.506, 236.463, 237.423)
Input <- data.frame(Date, CFC11)
# New Dates
Well1 <- c(2015.6, 2014.2, 2013.1)
Well2 <- c(2013.7, 2011.9, 2010)
NDates <- rbind(Well1, Well2)
NDates <- matrix(NDates, nrow = 2, ncol = 3)
# Input function
CFC11fun <- approxfun(Input$Date,Input$CFC11,rule=2)
# Apply the input function to the dates to get the input at the new dates
# rowwise
# this transposes the result, so I would need to transpose it back
t(apply(NDates,1,CFC11fun))
# looks at timing
microbenchmark(t(apply(NDates,1,CFC11fun)), times = 1000, unit = "us")
只需在整个矩阵上调用您的函数,并将结果整形为相同维度的矩阵:
matrix(CFC11fun(NDates), nrow=nrow(NDates))