在 data.frame 的每一行之间进行插值

Vin*_*ent 5 interpolation r

我希望以data.frame快速的方式在 a 的每一行之间重新采样和插值。如有必要,我不介意使用data.table或其他数据结构。这是一个可重现的示例:

df <- data.frame(x = c(0, 2, 10),
                 y = c(10, 12, 0))
Run Code Online (Sandbox Code Playgroud)

期望的输出:一个函数f(df, n),其中n是会导致以下结果的插值数:

df_int <- f(df, 1)

# That would produce :
# df_int <- data.frame(x = c(0, 1, 2, 6, 10),
#                      y = c(10, 11, 12, 6, 0))

df_int <- f(df, 3)

# That would produce :
# df_int <- data.frame(x = c(0, 0.5, 1, 1.5, 2, 4, 6, 8, 10),
#                      y = c(10, 10.5, 11, 11.5, 12, 9, 6, 3, 0))
Run Code Online (Sandbox Code Playgroud)

提出了一些解决方案approx,但在我的情况下不起作用。

Aur*_*èle 6

不考虑速度

\n
interpolate_vector <- function(x, n) {\n  Reduce(function(x, tail_x) {\n    c(head(x, -1), seq(tail(x, 1), tail_x[1], length.out = n + 2))\n  }, init = x[1], x = tail(x, -1))\n}\n\nf <- function(df, n) {\n  as.data.frame(lapply(df, interpolate_vector, n))\n}\n
Run Code Online (Sandbox Code Playgroud)\n
f(df, 1)\n
Run Code Online (Sandbox Code Playgroud)\n
interpolate_vector <- function(x, n) {\n  Reduce(function(x, tail_x) {\n    c(head(x, -1), seq(tail(x, 1), tail_x[1], length.out = n + 2))\n  }, init = x[1], x = tail(x, -1))\n}\n\nf <- function(df, n) {\n  as.data.frame(lapply(df, interpolate_vector, n))\n}\n
Run Code Online (Sandbox Code Playgroud)\n
f(df, 3)\n
Run Code Online (Sandbox Code Playgroud)\n
f(df, 1)\n
Run Code Online (Sandbox Code Playgroud)\n
\n

无向量Reduce和增长向量:

\n
interpolate_vector_2 <- function(x, n) {\n  res <- numeric(length = (length(x)-1) * (n+1) + 1)\n  for (i in head(seq_along(x), -1)) {\n    res[(i + (i-1)*n) : (i + i*n + 1)] <- \n      seq(x[i], x[i+1], length.out = n+2)\n  }\n  res\n}\n\nf_2 <- function(df, n) {\n  as.data.frame(lapply(df, interpolate_vector_2, n))\n}\n
Run Code Online (Sandbox Code Playgroud)\n
\n

基准模板(包括@Ma\xc3\xabl\的答案):

\n
   x  y\n1  0 10\n2  1 11\n3  2 12\n4  6  6\n5 10  0\n
Run Code Online (Sandbox Code Playgroud)\n

在此输入图像描述

\n