Reputation: 47
I am a beginner using R, and I am trying to write a simple quadratic function in R that accepts values for a, b, c and x and returns a value for y: y = a + bx + cx^2, and from that, create and save a vector, x, of 101 equally spaced values from -2 to 2 inclusive. Using the vector x just constructed, and the following values a = -1, b = 0, c = 1 with your function, calculate and save values for a vector, y.
My code so far is below:
MyFunction <- function(x){y = a + bx + cx^2^
}
x <- seq(from = -2, to = 2, length.out = 101)
print(x)
a=-1
b=0
c=1
As you can see I have some of the basics down, but am having trouble put the pieces together. Any help is greatly appreciated! Thanks in advance.
Upvotes: 2
Views: 11785
Reputation: 430
Putting all answer together from @m-dz and @eipi10, we have:
MyFunction <- function(x, a=-1, b=0, c=1){
a + b*x + c*x^2
}
x <- seq(from = -2, to = 2, length.out = 101)
result <- MyFunction(x)
> result
[1] 3.0000 2.8416 2.6864 2.5344 2.3856 2.2400 2.0976 1.9584 1.8224 1.6896 1.5600 1.4336 1.3104 1.1904 1.0736
[16] 0.9600 0.8496 0.7424 0.6384 0.5376 0.4400 0.3456 0.2544 0.1664 0.0816 0.0000 -0.0784 -0.1536 -0.2256 -0.2944
[31] -0.3600 -0.4224 -0.4816 -0.5376 -0.5904 -0.6400 -0.6864 -0.7296 -0.7696 -0.8064 -0.8400 -0.8704 -0.8976 -0.9216 -0.9424
[46] -0.9600 -0.9744 -0.9856 -0.9936 -0.9984 -1.0000 -0.9984 -0.9936 -0.9856 -0.9744 -0.9600 -0.9424 -0.9216 -0.8976 -0.8704
[61] -0.8400 -0.8064 -0.7696 -0.7296 -0.6864 -0.6400 -0.5904 -0.5376 -0.4816 -0.4224 -0.3600 -0.2944 -0.2256 -0.1536 -0.0784
[76] 0.0000 0.0816 0.1664 0.2544 0.3456 0.4400 0.5376 0.6384 0.7424 0.8496 0.9600 1.0736 1.1904 1.3104 1.4336
[91] 1.5600 1.6896 1.8224 1.9584 2.0976 2.2400 2.3856 2.5344 2.6864 2.8416 3.0000
plot(result)
Upvotes: 4
Reputation: 3961
First off, there is an extra ^ operator at the end of the quadratic formula. See this link for defining and plotting a simple quadratic formula in r: http://rstudio-pubs-static.s3.amazonaws.com/275_8e3191f1f68f46229b30c361c6778dec.html
Upvotes: 0