I'm trying to plot the following implicit formula in R:
1 = x^2 + 4*(y^2) + x*y
which should be an ellipse. I'd like to randomly sample the x values and then generate the graph based on those.
Here's a related thread, but the solutions there seem to be specific to the 3D case. This question has been more resistant to Googling that I would have expected, so maybe the R language calls implicit formulas something else.
Thanks in advance!
Two things you may not understand. When plotting implicit functions with that technique, you need to move all terms to the RHS of the function so that your implicit function becomes:
0 = -1+ x^2 + 4*(y^2) + x*y
Then using the contour value of zero will make sense:
x<-seq(-1.1,1.1,length=1000)
y<-seq(-1,1,length=1000)
z<-outer(x,y,function(x,y) 4*y^2+x^2+x*y -1 )
contour(x,y,z,levels=0)
I got a sign wrong on the first version. #mnels' was correct.
Related
This should hopefully not be a very hard question—I'm just not very experienced in R.
If I want to graph a simple sine wave, all I have to is:
x=seq(-20,20,0.001)
y=seq(-20,20,0.001)
y=sin(x)
plot(x,y,type="l")
But let's say I want to graph a relationship with trigonometric functions on both sides, such as sin(x) = cos(y). Typing:
sin(x) = cos(y)
Gives me the following error
Error in sin(x) = cos(y) : could not find function "sin<-"
Now, the obvious solution is to just rearrange it in terms of one variable, such as x = asin(cos(y)). But with much more complicated equations with multiple nested trigonometric functions on both sides, this no longer becomes viable.
I'm sure I'm missing something extremely obvious, but what is it?
If you want to plot the relationship sin on the x axis and cos on the y axis:
plot(sin(x), cos(y), type = "l")
Or did I misunderstand the question?
The error is caused by your equal sign. The expression sin(x) = cos(y) is an assignment. If you would like to check where they are equal, then you should write sin(x) == cos(x).
I found some posts and discussions about the above, but I'm not sure... could someone please check if I am doing anything wrong?
I have a set of N points of the form (x,y,z). The x and y coordinates are independent variables that I choose, and z is the output of a rather complicated (and of course non-analytical) function that uses x and y as input.
My aim is to find a set of values of (x,y) where z=z0.
I looked up this kind of problem in R-related forums, and it appears that I need to interpolate the points first, perhaps using a package like akima or fields.
However, it is less clear to me: 1) if that is necessary, or the basic R functions that do the same are sufficiently good; 2) how I should use the interpolated surface to generate a correct matrix of the desired (x,y,z=z0) points.
E.g. this post seems somewhat related to the problem I am describing, but it looks extremely complicated to me, so I am wondering whether my simpler approach is correct.
Please see below some example code (not the original one, as I said the generating function for z is very complicated).
I would appreciate if you could please comment / let me know if this approach is correct / suggest a better one if applicable.
df <- merge(data.frame(x=seq(0,50,by=5)),data.frame(y=seq(0,12,by=1)),all=TRUE)
df["z"] <- (df$y)*(df$x)^2
ta <- xtabs(z~x+y,df)
contour(ta,nlevels=20)
contour(ta,levels=c(1000))
#why are the x and y axes [0,1] instead of showing the original values?
#and how accurate is the algorithm that draws the contour?
li2 <- as.data.frame(contourLines(ta,levels=c(1000)))
#this extracts the contour data, but all (x,y) values are wrong
require(akima)
s <- interp(df$x,df$y,df$z)
contour(s,levels=c(1000))
li <- as.data.frame(contourLines(s,levels=c(1000)))
#at least now the axis values are in the right range; but are they correct?
require(fields)
image.plot(s)
fancier, but same problem - are the values correct? better than the akima ones?
I'm a new user to R, and I am trying to create a function that will simulate a random walk. The issue for me is trying to integrate some initial values smoothly. Say I have this basic function.
y(t) = y(t-2) + eps(t)
Epsilon (or eps(t)) will be the randomness factor. I want to define y(-1)=0, and y(0)=0.
Here is my code:
ran.walk=function(n){ # 'n' steps will be the input
eps=rnorm(n) # creates a vector taking random values from N(0,1)
y= c(eps[1], eps[2]) # this will set up my initial vector
for (i in 3:n){
ytemp = y[i-2] + eps[i] ## !!! problem is here. Details below !!!
y= c(y, ytemp)
}
return(y)
}
I'm trying to get this start adding y3, y4, y5, etc, but I think there is a flaw in this design... I'm not sure if I should just set up two separate lines, with an if statement: testing if n is even or odd, perhaps with:
if i%%2 == 1 #using modulus
Since,
y1= eps1,
y2= eps2,
y3= y1 + eps3,
y4= y2 + eps4,
y5= y3 + eps5 and so on...
Currently, I see the error in my code.
I have y1, and y2 concatenated, but I don't think it knows how to incorporate y[1]
Can I define beforehand somehow y[-1]=0, and y[0]=0 ? I tried this also and got an error.
Thank you kindly in advance for any assistance. This is first times attempting a for loop with recursion.
-N (sorry for any formatting issues, I had a lot of problems getting this question to go through)
I found that your odd and even series is independent one of the other. Assuming that it is the case, I just split the problem in two columns and use cumsum to get the random walk. The final data frame include the random numbers and the random walk, so you can compare it is working properly.
Hoping it helps
ran.walk=function(n) {
eps=rnorm(ceiling(n / 2)*2)
dim(eps) <- c(2,ceiling(n/2))
# since each series is independent, we can tally each one in its own
eps2 <- apply(eps, 1, cumsum)
# and just reorganize it
eps2 <- as.numeric(t(eps2))
rndwlk <- data.frame(rnd=as.numeric(eps), walk=eps2)
# remove the extra value if needed
rndwlk <- rndwlk[1:n,]
return(rndwlk)
}
ran.walk(13)
After taking a break with my piano, it came to me. It's funny how simple the answer becomes once you discover it... almost trivial.
Setting the initial value to be a vector, that is:
[y(1) = y(-1) + eps(1), y(2)= y(0) + eps(2)]
everything works out. It is still true that the evens and odds don't interact, but there is no reason to specify any of that.
The method to split the iterations with modulus, then concatenating it back into the main vector would also work, but is unnecessary and more complicated. Shorter is better for users and computers. As Einstein said, make it as simple as possible, but no simpler.
How to plot Leibniz series in R for above? Basically I am looking for R commands.
Let's see if I can cobble together an exact transliteration using Reduce which allows cumulative function applications to series. The :-operator is also quite handy for building the underlying series:
plot( pi/4 - Reduce( 'sum' ,
(-1)^(0:200)*(1/(1+2*(0:200))),
acc=TRUE) ) # preserves the intermediate values
This is definitely a homework assignment because I googled the same thing lol. I will help without giving away the answer because you'll learn better if you actually work through the assignment.
At this point, my class did not learn the Reduce function so as an alternative, what you can do is create a function that implements the series: 1 - 1/3 + 1/5 - 1/7 +......, for n iterations (n = 200).
Have the function return a list of values (this would be your y-axis values) and you can plot those for 0:200 (your x-axis values). Then plot a second line graph with y-axis as pi/4 minus the values returned by the function.
I plotted an expression curve, i.e.curve(-log((1-x)/0.9999)/x,ylim=c(0,4)).
However, I want to see the reverse relationship, i.e. y changes over x instead of x changes over y. Are there any R function can plot it automatically? Or a function that can solve the equation?
There are two obvious choices:
(i) derive the inverse function algebraically (trivial in this case),
That is, take y=-log((1-x)/0.9999) and make x the subject of the equation (which would require straightforward algebraic manipulation suitable for a question on math.SE if it's not obvious how to proceed)...
... and then use curve on the result of that, or
(ii) use plot rather than curve to plot a set of (x,y) pairs (set type="l" to get a curve), and simply interchange which is x and which is y in the call to plot.