Search code examples
rfunctionaveragetemperatureexp

How to craft this function in R?


I am currently trying to write a function that estimates energy expenditure of some lizards through E = e21.44 * (e(8.74901^10−20 / (1.3806488*10−23 *T). T in the equation is equal to the temperature in Kelvin. I know that if I were to plug in a temperature of 20ºC the function should give me an output of about 0.829. However, when I run the function (see below) I get 2.628622e-121. I believe it's the way I am stating how temperature is converted from Celsius to Kelvin is incorrect and I am currently stuck on it.

TempKelvin <- 273.15
Energy = function(TempKelvin = 273.15 {
exp(24.11) * exp(-8.74901*10^20 / (1.3806488*10^-23 * (T + TempKelvin)))
}
Energy(T = 28)

Solution

  • There are several problems:

    • the call to the Energy function uses a T argument but that function, as defined in the question, has no T argument
    • T also means TRUE in R. Use a different name. T will be interpreted as 1 when used in a numeric context unless overwritten. e.g. T+8 equals 9 by default in R.
    • the formula in the question uses 8.74901 but the code uses the negative of that value. Which is correct?
    • use proper exponential notation for R constants, e.g. 1.38064852e−23
    • some of the digits of the Boltzmann constant (the one multiplying the temperature) are incorrect.
    • although adding 273.15 is the correct Celsius to Kelvin conversion formula I noticed that if we use 273 instead of the more accurate 273.15 then we do get the assumed answer.

    Note that because the answer depends on celsius and 273.15 only through their sum we can get the effect of using 273 instead of 273.15 like this:

    celsius + 273 
    = (celsius - 0.15) + 273.15
    

    That is passing the function 20-0.15 instead of 20 effectively uses 20 with 273 instead of using 20 with 273.15 .

    Energy <- function(celsius) {
      exp(21.44) * exp(-8.74901e−20 / (1.38064852e−23 * (celsius + 273.15)))
    }
    
    # match assumed answer (despite assumed answer being slightly wrong)
    Energy(20 - 0.15)  
    ## [1] 0.8289531
    
    # correct answer
    Energy(20)
    ## [1] 0.8381777