我試圖掰開將R代碼this post:瞭解[R卷積碼sapply()
x <- c(0.17,0.46,0.62,0.08,0.40,0.76,0.03,0.47,0.53,0.32,0.21,0.85,0.31,0.38,0.69)
convolve.binomial <- function(p) {
# p is a vector of probabilities of Bernoulli distributions.
# The convolution of these distributions is returned as a vector
# `z` where z[i] is the probability of i-1, i=1, 2, ..., length(p)+1.
n <- length(p) + 1
z <- c(1, rep(0, n-1))
sapply(p, function(q) {z <<- (1 - q) * z + q * (c(0, z[-n])); q})
z
}
convolve.binomial(x)
[1] 5.826141e-05 1.068804e-03 8.233357e-03 3.565983e-02 9.775029e-02
[6] 1.804516e-01 2.323855e-01 2.127628e-01 1.394564e-01 6.519699e-02
[11] 2.141555e-02 4.799630e-03 6.979119e-04 6.038947e-05 2.647052e-06
[16] 4.091095e-08
我RStudio試過debugging
,但它仍然是不透明的。
問題出在線:sapply(p, function(q) {z <<- (1 - q) * z + q * (c(0, z[-n])); q})
。
我想在調用convolve.binomial(x)
p = q = x
的上下文中。至少我得到了相同的結果,如果我拉的功能之外的線條和運行sapply(x, function(x) {z <<- (1 - x) * z + x * (c(0, z[-n])); x})
:
x <- c(0.17,0.46,0.62,0.08,0.40,0.76,0.03,0.47,0.53,0.32,0.21,0.85,0.31,0.38,0.69)
n <- length(x) + 1
z <- c(1, rep(0, n-1))
# [1] 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
sapply(x, function(x) {z <<- (1 - x) * z + x * (c(0, z[-n])); x})
z # Is extracted by calling it and contains the correct result
我的問題是:
- 什麼是內
sapply()
結束;q}
的目的是什麼? - 它與
<<-
符號有什麼關係,意思是讓z
可以在sapply()
的「隱式」循環之外訪問?
下面你可以看到我的問題 「黑客」 這行代碼:
(x_complem = 1 - x)
sapply(x, function(x) {z <<- x_complem * z + x * (c(0, z[-n])); x})
z # Returns 16 values and warnings
z_offset = c(0, z[-n])
# [1] 0 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0
sapply(x, function(x) {z <<- (1 - x) * z + x * z_offset; x})
z # Returns different values.
沒有'返回'語句的中間結果,r會返回最後eval的結果。它看起來功能的功能因此是3倍。要在全局範圍內聲明'z',計算'z',然後返回輸入'q'。 'q'作爲返回值可能只是爲了協助調試或者可能將其傳遞給另一個函數。 – varontron
'z'變量既可以作爲中間結果的集合存儲庫,也可以作爲關注該變量的下一個位置的移位運算符。 –
@ 42-你能否詳細說明在一個簡單的情況下會發生什麼操作,比如'x < - c(2,3','convolve.binomial(x)',我會很樂意接受答案。我理解了卷積的一般原理,但是我遇到了與這個'sapply()'函數協調的問題。 – Toni