2015-10-15 84 views
0

我有两个变量的函数和每个变量的时间间隔。最后我想提出一个热点图,其中Point(x,y)表示该点处函数的值,所以我想在相应的时间间隔内为两个值的每个组合计算函数。 该函数有两个double值。 我找到了outer()函数,但我不完全确定它正在做我想要的。有没有快速解决这个问题?优雅地评估R中两个值向量的两个变量的函数?

谢谢!

+0

请分享一个最小可重现的例子,即数据和代码尝试。 – 2015-10-15 08:15:40

回答

0

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)" 
>