0
我有兩個變量的函數和每個變量的時間間隔。最後我想提出一個熱點圖,其中Point(x,y)表示該點處函數的值,所以我想在相應的時間間隔內爲兩個值的每個組合計算函數。 該函數有兩個double值。 我找到了outer()函數,但我不完全確定它正在做我想要的。有沒有快速解決這個問題?優雅地評估R中兩個值向量的兩個變量的函數?
謝謝!
我有兩個變量的函數和每個變量的時間間隔。最後我想提出一個熱點圖,其中Point(x,y)表示該點處函數的值,所以我想在相應的時間間隔內爲兩個值的每個組合計算函數。 該函數有兩個double值。 我找到了outer()函數,但我不完全確定它正在做我想要的。有沒有快速解決這個問題?優雅地評估R中兩個值向量的兩個變量的函數?
謝謝!
outer
確實是一個好主意,假設(x,y)點形成一個矩形網格。例如,它至少比mapply
更快。
f <- function(x,y){sprintf("heat(%3.1f,%3.1f)",x,y)}
X <- 0.5*(0:12)
Y <- 0.3*(0:3)
X.matrix <- matrix(X,length(X),length(Y))
Y.matrix <- matrix(Y,length(X),length(Y),byrow=TRUE)
system.time(for (i in 1:100000){ heat.1 <- outer(X,Y,"f") })
system.time(for (i in 1:100000){ heat.2 <- matrix(mapply("f",X.matrix,Y.matrix),length(X))})
。
> system.time(for (i in 1:100000){ heat.1 <- outer(X,Y,"f") })
user system elapsed
22.71 0.00 22.83
> system.time(for (i in 1:100000){ heat.2 <- matrix(mapply("f",X.matrix,Y.matrix),length(X))})
user system elapsed
57.03 0.02 57.53
。
> identical(heat.1,heat.2)
[1] TRUE
> heat.1
[,1] [,2] [,3] [,4]
[1,] "heat(0.0,0.0)" "heat(0.0,0.3)" "heat(0.0,0.6)" "heat(0.0,0.9)"
[2,] "heat(0.5,0.0)" "heat(0.5,0.3)" "heat(0.5,0.6)" "heat(0.5,0.9)"
[3,] "heat(1.0,0.0)" "heat(1.0,0.3)" "heat(1.0,0.6)" "heat(1.0,0.9)"
[4,] "heat(1.5,0.0)" "heat(1.5,0.3)" "heat(1.5,0.6)" "heat(1.5,0.9)"
[5,] "heat(2.0,0.0)" "heat(2.0,0.3)" "heat(2.0,0.6)" "heat(2.0,0.9)"
[6,] "heat(2.5,0.0)" "heat(2.5,0.3)" "heat(2.5,0.6)" "heat(2.5,0.9)"
[7,] "heat(3.0,0.0)" "heat(3.0,0.3)" "heat(3.0,0.6)" "heat(3.0,0.9)"
[8,] "heat(3.5,0.0)" "heat(3.5,0.3)" "heat(3.5,0.6)" "heat(3.5,0.9)"
[9,] "heat(4.0,0.0)" "heat(4.0,0.3)" "heat(4.0,0.6)" "heat(4.0,0.9)"
[10,] "heat(4.5,0.0)" "heat(4.5,0.3)" "heat(4.5,0.6)" "heat(4.5,0.9)"
[11,] "heat(5.0,0.0)" "heat(5.0,0.3)" "heat(5.0,0.6)" "heat(5.0,0.9)"
[12,] "heat(5.5,0.0)" "heat(5.5,0.3)" "heat(5.5,0.6)" "heat(5.5,0.9)"
[13,] "heat(6.0,0.0)" "heat(6.0,0.3)" "heat(6.0,0.6)" "heat(6.0,0.9)"
>
請分享一個最小可重現的例子,即數據和代碼嘗試。 – 2015-10-15 08:15:40