优雅地评估R中两个值向量的两个变量的函数?

时间:2015-10-15 08:14:36

标签: r heatmap

我有两个变量的函数和每个变量的间隔。最后我想提出一个热图,其中Point(x,y)表示该点处函数的值,因此我想评估相应区间内两个值的每个组合的函数。 该函数有两个double值。 我发现了outer()函数,但我并不完全确定它是在做我想要的。对此有什么快速解决方案吗?

谢谢!

1 个答案:

答案 0 :(得分: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)"
>