在R中插值数据

6

假设我在R中有一个3×5的矩阵:

4  5  5  6  8
3  4  4  5  6
2  3  3  3  4

我希望对这些值进行插值,以创建一个大小为15x25的矩阵。我还想指定插值是线性的、高斯的等等。我该怎么做? 例如,如果我有一个像这样的小矩阵:
2 3
1 3

我希望它变成3乘3的样子,那么它可能看起来像这样

  2    2.5   3
  1.5  2.2   3
  1    2     3 

1
不清楚你想要什么,请提供样本输出。 - Joshua Ulrich
这篇帖子可能会有所帮助?https://dev59.com/NXA75IYBdhLWcg3w0cjx - Arun
@Arun 看起来很有用,不过 R 中肯定有内置函数可以做到这一点... - CodeGuy
2个回答

6
app <- function(x, n) approx(x, n=n)$y # Or whatever interpolation that you want

apply(t(apply(x, 1, function(x) app(x, nc))), 2, function(x) app(x, nr))
     [,1] [,2] [,3]
[1,]  2.0 2.50    3
[2,]  1.5 2.25    3
[3,]  1.0 2.00    3

针对我的回答进行跟进:如果我正确地阅读了这段代码,将ncnr设置为所需输出矩阵的列数/行数将允许任意不对称扩展。 - Carl Witthoft

0

很久以前我写过一个类似的玩具,只是我从来没有定义插值函数。还有raster::disaggregate

zexpand<-function(inarray, fact=2, interp=FALSE,  ...)  {
# do same analysis of fact to allow one or two values, fact >=1 required, etc.
fact<-as.integer(round(fact))
switch(as.character(length(fact)),
            '1' = xfact<-yfact<-fact,
            '2'= {xfact<-fact[1]; yfact<-fact[2]},
            {xfact<-fact[1]; yfact<-fact[2];warning(' fact is too long. First two values used.')})
if (xfact < 1) { stop('fact[1] must be > 0') } 
if (yfact < 1) { stop('fact[2] must be > 0') }
bigtmp <- matrix(rep(t(inarray), each=xfact), nrow(inarray), ncol(inarray)*xfact, byr=T)  #does column expansion
bigx <- t(matrix(rep((bigtmp),each=yfact),ncol(bigtmp),nrow(bigtmp)*yfact,byr=T))
# the interpolation would go here. Or use interp.loess on output (won't
# handle complex data). Also, look at fields::Tps which probably does
# a much better job anyway.  Just do separately on Re and Im data
return(invisible(bigx))
}

谢谢您的回复。这个答案与Math Lundberg上面的答案有何不同或更好? - CodeGuy
@CodeGuy 如果我实际上在里面放了一个插值函数(基本上替换了rep函数,它只是复制行或列),它几乎做的事情一模一样,只是我允许在列和行维度中进行不同的扩展。正如Matthew所写的那样,您也可以在他的代码中随意更换你想要的插值器。 - Carl Witthoft

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接