Search code examples
rcalculated-columnsexponential

How to do exponential calculation with matrix?


I want to calculate exponential with a matrix and vector. The matrix is as below

 ID     var_0     var_01    var_02   var_03 
 1        1         2        3        4
 2        5         6        7        8
 3        9         10       11       12
 ...

and vector is (0.1,0.2,0.3,0.4)

I want to get the result as below

 ID       var_0   var_01     var_02   var_03 
 1        1^0.1     2^0.2    3^0.3    4^0.4
 2        5^0.1     6^0.2    7^0.3    8^0.4
 3        9^0.1     10^0.2   11^0.3    12^0.4
 ...

That is, I want to get (ith var)^ith vector for each ID


Solution

  • You can use R's recycling of vectors. Transpose your matrix so that the power calculations are applied in the correct order and then transpose back.

    (m <- matrix(1:12, nrow=3, ncol=4, byrow=TRUE))
    #       [,1] [,2] [,3] [,4]
    # [1,]    1    2    3    4
    # [2,]    5    6    7    8
    # [3,]    9   10   11   12
    
    p <- 1:4
    
    t(t(m)^p)
    #       [,1] [,2] [,3]  [,4]
    # [1,]    1    4   27   256
    # [2,]    5   36  343  4096
    # [3,]    9  100 1331 20736