我對rollapply
的width
選項的理解是,它指定了函數將在其上運行的窗口大小,並且by
選項指定此窗口的移位大小。這是我的數據集:即確認關於動物園的幾個問題:: rollapply
> dataset <- as.vector(t(cbind(5:1, 1:5)))
> dataset
[1] 5 1 4 2 3 3 2 4 1 5
這裏是一個例子,我已經寫了上面:
> w3b3 <- rollapply(dataset, width = 3, by=3, FUN = print, align="left")
[1] 5 1 4
[1] 2 3 3
[1] 2 4 1
> w3b2 <- rollapply(dataset, width = 3, by=2, FUN = print, align="left")
[1] 5 1 4
[1] 4 2 3
[1] 3 3 2
[1] 2 4 1
> w2b3 <- rollapply(dataset, width = 2, by=3, FUN = print, align="left")
[1] 5 1
[1] 2 3
[1] 2 4
> w3b1 <- rollapply(dataset, width = 3, by=1, FUN = print, align="left")
[1] 5 1 4
[1] 1 4 2
[1] 4 2 3
[1] 2 3 3
[1] 3 3 2
[1] 3 2 4
[1] 2 4 1
[1] 4 1 5
# ACCORDING OT MAN WHEN NO VALUE IS USED THEN by=1 (SAME AS ABOVE)
> w3b1 <- rollapply(dataset, width = 3, FUN = print, align="left")
[1] 5 1 4
[1] 1 4 2
[1] 4 2 3
[1] 2 3 3
[1] 3 3 2
[1] 3 2 4
[1] 2 4 1
[1] 4 1 5
> w1b1 <- rollapply(dataset, width = 1, by=1, FUN = print, align="left")
[1] 5
[1] 1
[1] 4
[1] 2
[1] 3
[1] 3
[1] 2
[1] 4
[1] 1
[1] 5
儘管我有幾個問題:
1)爲什麼這樣一個返回錯誤而max(20)
正在運行?一切都是相同的,所不同print
最後一個例子是替換max
:
> w1b1 <- rollapply(dataset, width = 1, by=1, FUN = max, align="left")
Error in if (is.na(a) || is.na(rval[i = 1]) || a == rval[i - 1]) max(xc[(i - :
missing value where TRUE/FALSE needed
如何調試這些類型的*apply
家庭功能錯誤?
2)在with
選項中使用大於1的向量的目的是什麼?以及爲什麼後面的代碼打印一個數字以輸出奇數位置,但將奇數位置的兩個數字分配給w12
變量?
> w12 <- rollapply(dataset, width = c(1,2), FUN = print, align="left")
[1] 5
[1] 1 4
[1] 4
[1] 2 3
[1] 3
[1] 3 2
[1] 2
[1] 4 1
[1] 1
> w12
[,1] [,2]
[1,] 5 5
[2,] 1 4
[3,] 4 4
[4,] 2 3
[5,] 3 3
[6,] 3 2
[7,] 2 2
[8,] 4 1
[9,] 1 1
# SAME AS ABOVE (ACCORDING TO MAN by IS USED ONLY IF width IS OF LENGTH 1)
> w12 <- rollapply(dataset, width = c(1,2), by=10, FUN = print, align="left")
[1] 5
[1] 1 4
[1] 4
[1] 2 3
[1] 3
[1] 3 2
[1] 2
[1] 4 1
[1] 1
> w12
[,1] [,2]
[1,] 5 5
[2,] 1 4
[3,] 4 4
[4,] 2 3
[5,] 3 3
[6,] 3 2
[7,] 2 2
[8,] 4 1
[9,] 1 1
3)通過向量和列表width
參數之間的區別是什麼(相比以前的輸出,這是完全不同的)?
> rollapply(dataset, width = list(1,2), FUN = print, align="left")
[1] 1
[1] 2
[1] 2
[1] 3
[1] 3
[1] 4
[1] 4
[1] 5
[1] 5
[1] 1 2 2 3 3 4 4 5 5
4)by.column
是做什麼的?我期待它與矩陣有關,所以我嘗試了以下內容:
> mtrx <- matrix(c(1:30), nrow=10)
> mtrx
[,1] [,2] [,3]
[1,] 1 11 21
[2,] 2 12 22
[3,] 3 13 23
[4,] 4 14 24
[5,] 5 15 25
[6,] 6 16 26
[7,] 7 17 27
[8,] 8 18 28
[9,] 9 19 29
[10,] 10 20 30
# THIS IS OK
> rollapply(mtrx, width = 2, by = 2, FUN = max, align = "left", by.column=T)
[,1] [,2] [,3]
[1,] 2 12 22
[2,] 4 14 24
[3,] 6 16 26
[4,] 8 18 28
[5,] 10 20 30
# BUT WHAT IS THIS?
> rollapply(mtrx, width = 2, by = 2, FUN = max, align = "left", by.column=F)
[1] 22 24 26 28 30
你應該嘗試限制你的帖子每個問題,例如,因爲我可以給你一些提示,但不是所有的問題:1)不確定,bu有趣的是,min沒有錯誤地工作; 2)變量窗口; 3)不確定; 4)??; 5)最後一個例子是給你的最大行數爲2的窗口,所以用min或median再次嘗試,看看會發生什麼 – rawr
@rawr謝謝你的回覆。你能否試着進一步解釋2,4(作爲更正前的5)作爲答案?謝謝。 –