# KevCaz's Website

## Miscelleneous

I always forget how to convert Fahrenheit to Celsius and conversely, which I find very frustrating – for the record the current definition is:

$$T(°F) = T(°C)\frac{9}{5}+32$$

Yesterday, after looking for the umpteenth times the above equation I decided to create a small function that would handle the conversion. I first thought that I could create a 2-lines function just for this specific unit conversion when I realize that there is a R 📦 dedicated to units manipulation: units that depends on the C library libdunits2 and is required to install 📦 sf. After a couple of minutes reading the documentation 📖, I figured out how to create a simple but robust unit converter with one line of code, and so I did:

 1 2 3  R> conv <- function(x, from = "fahrenheit", to = "celsius") { units::as_units(0, to) + units::as_units(as.numeric(x), from) } 

I appended this function to my .Rprofile and now, it is available when I work with R. Here are a couple of examples:

 1 2 3 4 5 6 7 8 9  # Fahrenheit => Celsius (default) R> conv(350) 176.6667 [°C] # Day => second R> conv(1.5, "d", "s") 129600 [s] # calorie => Joule R> conv(1, "cal", "J") 4.1868 [J] 

I also created a shell function calling the R function above, so that I quickly convert units in a Terminal!

 1 2 3 4 5 6  # shell function convR() { FROM=${2:-fahrenheit} TO=${3:-celsius} Rscript -e "conv('$1', '$FROM', '$TO')" }  For instance:  1 2 3 4  $ convR 420 215.5556 [°C] \$ convR 3600 km/h m/s 1000 [m/s] 

I will likely use littler to call the R function in a shell and if I do so, I will report how to on this site!