mapply error: 'length.out' must be a non-negative number

mapply error: 'length.out' must be a non-negative number

我创建了以下简单函数:

fillampenv <- function(samples, samprate, rise, fall){
  # Create output vector
  v <- vector("numeric", samples)
  # Fill output vector
  v <- c(seq(0, 1, length = rise * samprate),
         seq(1, 1, length = (((samples/samprate) -
                                (rise + fall)) * samprate) -1),
         seq(1, 0, length = fall * samprate))
  return(v)
}

我想在数据帧的每一行上调用:

df <- structure(list(samples = c(17640, 17640, 17640, 17640, 17640), samprate = c(44100, 44100, 44100, 44100, 44100), rise = c(0.75, 0.75, 0.75, 0.75, 0.75), fall = c(0.3, 0.3, 0.3, 0.3, 0.3)), class = "data.frame", row.names = c(NA, -5L))

但是,当我尝试使用以下方法执行此操作时(它适用于我创建的其他功能):

ampenvs <- mapply(fillampenv,
                  samples = df$samples,
                  samprate = df$samprate,
                  rise = df$rise,
                  fall = df$fall)

我收到错误:

Error in seq.default(1, 1, length = (((samples/samprate) - (rise + fall)) *  : 
  'length.out' must be a non-negative number

知道为什么吗?我正在努力弄清楚为什么它不能特别适用于此功能(而其他功能可以正常工作)。

您的函数导致传递给 seq 的负 length.out 参数。例如,

> df %>% mutate(x = (((samples/samprate) -
+                       (rise + fall)) * samprate) -1)
  samples samprate rise fall      x
1   17640    44100 0.75  0.3 -28666
2   17640    44100 0.75  0.3 -28666
3   17640    44100 0.75  0.3 -28666
4   17640    44100 0.75  0.3 -28666
5   17640    44100 0.75  0.3 -28666

无论你在哪里遇到这个问题,你都必须将你的数字解析为你想要的数字,如 Float、Integer 和 ...