1

I have generated 2 variables "x" and "y".

a = 2
t = NULL
for(a in 2:435){ 
  t[a] <- sum(litter[a,2:13] * cos(angles))
}
x <- t/n  

b = 2
u = NULL
for(b in 2:435){ 
  u[b] <- sum(litter[b,2:13] * sin(angles))
}
y <- u/n

Now, I need to generate a new variable "r.angle" with the following conditions:

if (x>0)  r.angle <- atan(y/x)
if (x<0)  r.angle <- atan(y/x) + pi 
if (x==0) r.angle <- NA 
ifelse(r.angle<0, r.angle <- r.angle + (2*pi), NA)

I am unsure on how to write this out in a loop that iterates over rows.

  • This [question](http://stackoverflow.com/questions/21484558/how-to-calculate-wind-direction-from-u-and-v-wind-components-in-r) might be useful. –  Apr 16 '15 at 05:10
  • Hi! No, it is not. The person is still correcting for other variables. –  Apr 16 '15 at 05:22
  • It would be helpful, if you could tell me how to put this in a if loop, as I am an amateur. –  Apr 16 '15 at 05:22

1 Answers1

1

If I understood your problem correct, you could just create a function and apply this to your data like this:

toyData <- data.frame(x=1:9, y=9:1)

toyFunction <- function(inputData){
  x <- inputData[1]
  y <- inputData[2]
  if (x>0)  r.angle <- atan(y/x)
  if (x<0)  r.angle <- atan(y/x) + pi 
  if (x==0) r.angle <- NA 
  ifelse(r.angle<0, r.angle <- r.angle + (2*pi), NA)
  r.angle
}

apply(toyData,1,toyFunction)

Probably you'll need to adjust this to your actual data.

Daniel Fischer
  • 3,280
  • 1
  • 18
  • 29