0

I am trying to build a function to calculate the magnitude and direction of vector operation. In order to solve the problem that inverse trig function is restricted within the domain of pi/2 and -pi/2, I need to add 2pi to the e if e is less than 0. But I encounter the "Error: unexpected '}' in "}" once I added the if else line. Would anyone be able to explain to me why?

vectorMD <- function(x){
    c=x[1:2]-x[3:4]
    mt  <- function(x) {round(sqrt(sum(x^2)),1)}
    d <- round(mt(c),1)
    e <- round(atan(c[2]/c[1]),1)
if(e < 0){e <- e+2*2pi
    return(e)} 
paste("magnitude =",d,"direction =",e)
}
akrun
  • 874,273
  • 37
  • 540
  • 662
DSL
  • 169
  • 7

2 Answers2

1

Instead of 2pi in if condition you have to give as 2*pi since pi is already a value like 3.14 you can't specify it as 2pi which is like 23.14 so you have to specify it has 2*pi which is like 2*3.14

The code:

vectorMD <- function(x){
    c=x[1:2]-x[3:4]
    mt  <- function(x) {round(sqrt(sum(x^2)),1)}
    d <- round(mt(c),1)
    e <- round(atan(c[2]/c[1]),1)
    if(e < 0){e <- e+2*2*pi
        return(e)} 
    paste("magnitude =",d,"direction =",e)
   }
The6thSense
  • 8,103
  • 8
  • 31
  • 65
0

Try this, put function "mt" outside of function "vector".

mt  <- function(x) 
{
    round(sqrt(sum(x^2)),1)
}

vectorMD <- function(x)
{
    c=x[1:2]-x[3:4]

    d <- round(mt(c),1)
    e <- round(atan(c[2]/c[1]),1)

    if(e < 0)
    {
        e <- e+2*2pi
        return(e)
    }

    paste("magnitude =",d,"direction =",e)
}
Nico
  • 374
  • 2
  • 4
  • 17