Reputation:
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.
Upvotes: 1
Views: 1999
Reputation: 3380
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.
Upvotes: 1