在R的序列中间添加零(如上采样)

问题描述 投票:1回答:2

我想知道R中是否有用于向上采样的函数,因为我什至找不到类似于Matlab upsample(x,upsampling_factor)的函数。有一些名为upsample的函数,但是它们使用起来非常混乱,我需要一些东西在两个数字之间添加预定义的零。将输入信号X设为[1,2,3,4]并将其转换为[1 0 0 2 0 0 3 3 0 0 4 0 0]的任何其他函数都可以。这就像上采样系数3。

r function sampling
2个回答
1
投票

here获得线索的几个选项:

upsample1 = function(x, upsampling_factor)
  c(rbind(x, matrix(0, nc=length(x), nr=upsampling_factor-1)))    

upsample2 = function(x, upsampling_factor){
  v = numeric(length(x)*upsampling_factor)
  v[seq(1, length(x)*upsampling_factor, by=upsampling_factor)]=x
  v
}      

upsample3 = function(x, upsampling_factor) 
  c(kronecker(x, c(1, rep(0, upsampling_factor-1))))

# d.b -- this looks a wee bit faster
upsample4 = function(x, upsampling_factor) 
   replace(rep(0, upsampling_factor * length(x)), 
      1:(upsampling_factor*length(x)) %% upsampling_factor == 1, x)

为了利息

all.equal(upsample1(x=1e5, 4), upsample2(x=1e5, 4))
all.equal(upsample3(x=1e5, 4), upsample2(x=1e5, 4))

microbenchmark::microbenchmark(upsample1(x=1e5, 4),
                               upsample2(x=1e5, 4),
                               upsample3(x=1e5, 4),
                               upsample4(x=1e5, 4))

# Unit: microseconds
#                     expr    min      lq     mean  median      uq     max neval cld
#  upsample1(x = 1e+05, 4)  9.080 10.6515 11.72813 11.8735 12.4325  24.025   100  a  
#  upsample2(x = 1e+05, 4) 38.902 42.6740 45.14167 44.1400 46.4450  90.864   100  b 
#  upsample3(x = 1e+05, 4) 62.368 65.8610 69.69082 67.4325 70.6795 187.455   100  c
#  upsample4(x = 1e+05, 4)  7.613  8.8705  9.57149  9.5690 10.0570  19.137   100  a  

2
投票
x = 1:4
n = 3

unlist(Map(function(a, b) c(a, rep(0, b - 1)), x, n))
#OR
replace(rep(0, n * length(x)), seq_along(x) * n - (n - 1), x)
#OR
c(replace(matrix(0, n, length(x)), cbind(1, seq_along(x)), x))
#OR
replace(rep(0, n * length(x)), 1:(n*length(x)) %% n == 1, x)
# [1] 1 0 0 2 0 0 3 0 0 4 0 0
© www.soinside.com 2019 - 2024. All rights reserved.