sapply 在计算梯度时不使用 return(数字)向量

sapply doesn't return (numeric) vector when calculating gradients

我正在使用

计算梯度值
  DF$gradUx <- sapply(1:nrow(DF), function(i) ((DF$V4[i+1])-DF$V4[i]), simplify = "vector") 

但是在检查 class(DF$gradUx) 时,我仍然得到一个列表。我想要的是一个数字向量。我做错了什么?

Browse[1]> head(DF)
  V1 V2            V3           V4      
1  0  0 -2.913692e-09 2.913685e-09                          
2  1  0  1.574589e-05 3.443367e-09 
3  2  0  2.111406e-05 3.520451e-09 
4  3  0  2.496275e-05 3.613013e-09 
5  4  0  2.735775e-05 3.720385e-09 
6  5  0  2.892444e-05 3.841937e-09 

只有当所有 return 值的长度都为 1 时,您才会得到一个数值向量。更准确地说,如果所有 return 值的长度都相同,您将得到一个数组。来自 ?sapply "Details":

Simplification in 'sapply' is only attempted if 'X' has length greater than zero and if the return values from all elements of 'X' are all of the same (positive) length. If the common length is one the result is a vector, and if greater than one is a matrix with a column corresponding to each element of 'X'.

i == 0 时,您的公式将 return numeric(0),因此整个 return 将是一个列表。

您需要更改您的计算以考虑在您的向量边界之外的索引。 DF$V4[1-1] returns numeric(0)DF$V4[nrow(DF)+1] returns NA。修正这个逻辑,你应该解决矢量问题。

Edit:由于历史原因,原始问题错误地将差异计算为 DF$V4[i+1])-DF$V4[i-1],给出了 lag-2 差异,而最近编辑的问题(和OP 的意图)显示出滞后 1 差异。

而不是 sapply 我应该简单地使用 diff(DF$V3) 并将其写入新的 data.frame:

gradients = data.frame(gradUx=diff(DF$V3),gradUy=diff(DF$V4))

如果将观察值排列起来,则可以很容易地将此​​计算矢量化。我使用 headtail 删除前 2 个和最后 2 个观察值:

gradUx <- c(NA, tail(df$V4, -2) - head(df$V4, -2), NA)

> gradUx
[1]          NA 6.06766e-10 1.69646e-10 1.99934e-10 2.28924e-10          NA

它以矢量形式提供与您的方法相同的值:

> sapply(1:nrow(df), function(i) ((df$V4[i+1])-df$V4[i-1]), simplify = "vector")
[[1]]
numeric(0)

[[2]]
[1] 6.06766e-10

[[3]]
[1] 1.69646e-10

[[4]]
[1] 1.99934e-10

[[5]]
[1] 2.28924e-10

[[6]]
[1] NA