 # Error while creating a function

I am trying to create a function for finding out the positive root for a quadratic equation. I have written the following code for the same but I keep getting an error stating that b not found and the following appears:

Positive_Root <- function(x,y,z){

• ``````x <- a
``````
• ``````y <- b
``````
• ``````z <- c
``````
• ``````-b+sqrt(b^2-4*a*c)/2*a
``````
• }

Positive_Root(2,-1,-4)
Error in Positive_Root(2, -1, -4) : object 'b' not found

You're getting that error because you're assigning non-existent variables `a`, `b` and `c` to `x`, `y` and `z` respectively. In fact, you don't need the latter at all. You could simplify your function as follows:

``````Positive_Root <- function(a, b, c) {
-b + sqrt(b^2 - 4*a*c) / 2*a
}

Positive_Root(2, -1, -4)
#>  6.744563
``````

Created on 2020-03-23 by the reprex package (v0.3.0)

Sir. Thank you for your help. Just an additional doubt. I wrote the code for n(n+1)/2 in a similar manner and didn't receive am error. Could you help in differentiating the two codes.

Sum_first_n <- function(x){

• n <- x
• (n*(n+1))/2
• }

Sum_first_n(5)
 15

The difference is that the order of variable assignment is reversed. In `Sum_first_n()`, you are assigning `x` to `n` and `x` is intialized with the value 5 when you call the function.

If you change `Positive_Root()` as shown below it will work fine. But there's no need to create these extra variables as I explained in my previous post.

``````Positive_Root <- function(x, y, z) {
a <- x
b <- y
c <- z

-b + sqrt(b^2 - 4*a*c) / 2*a
}

Positive_Root(2, -1, -4)
#>  6.744563
``````

Created on 2020-03-23 by the reprex package (v0.3.0)

Thanks a lot. It was of great help. :]

yes, and as siddharthprabhu says,
as you assign x directly to n, there is no purpose, and these are just anonymous labels, they are not special. so both of these would work

``````Sum_first_n <- function(x){
(x*(x+1))/2
}
Sum_first_n(5)
 15

Sum_first_n <- function(n){
(n*(n+1))/2
}
Sum_first_n(5)
 15``````
1 Like

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.