Calculating wind direction from U and V components of the wind using lapply or ifelse

r

Solution

First define the function to do the calculation:

windDir <- function(u, v) {
  if(v > 0)         ((180 / pi) * atan(u/v) + 180)
  if(u < 0 & v < 0) ((180 / pi) * atan(u/v) + 0)
  if(u > 0 & v < 0) ((180 / pi) * atan(u/v) + 360)
}

Then apply it to each row. Here I'm using `ddply`, which is a nice "apply" variety for data frames:

> library(plyr)
> ddply(data, 'DateTime', summarize, windDir=windDir(Ucomp, Vcomp))
  DateTime  windDir
1     1981 278.0232
2     1982 276.0232
3     1983 280.2760
4     1984 277.1531
5     1985 280.0370
6     1986 279.7517

Problem

Averaging scalar wind direction data yields inaccurate values due to the compass headings ranging from 0-360 degrees, so I have converted my list to u and v components from the magnitude and wind direction angles already. In order to back out the proper wind direction, for averaging purposes, I need to develop some sort of apply, ifelse, function for the 3 following scenarios: ``` V > 0...((180 / pi) * atan((Ucomp/Vcomp)) + 180) U and V < 0...((180 / pi) * atan((Ucomp/Vcomp)) + 0) U > 0 and V < 0...((180 / pi) * atan((Ucomp/Vcomp)) + 360) ``` In the data set I am looking to analyze, Ucomp is greater than 0 and Vcomp is less than zero, but there will undoubtedly be scenarios where all 3 will pan out, so I need a function to parse through and calculate iteratively and applying the correct formula for each time step. I have not used lapply or functions before, so me playing around with them has not worked. I provide a sample of data below... ``` DateTime Wind.Spd Wind.Direction Air.Density Temp.C GEP.GE16XLE GCF.GE16XLE Ucomp Vcomp 1 1981 7.662370 248.3395 0.9148207 11.28967 597.7513 37.35946 5.253453 -0.7404972 2 1982 8.199412 251.6763 0.9172176 10.12751 678.8595 42.42872 5.867979 -0.6191475 3 1983 8.188782 251.7889 0.9162767 10.30619 667.9461 41.74663 5.777208 -1.0473982 4 1984 7.942632 246.7908 0.9174074 10.05093 642.6374 40.16484 5.415773 -0.6796723 5 1985 8.016558 252.7305 0.9171721 10.38414 654.2588 40.89117 5.649406 -0.9999082 6 1986 7.739984 249.6431 0.9158740 10.99859 607.0542 37.94089 5.305971 -0.9118965 ```

Original source