How to define a range in R of the following form?
(0, 5]
Does the range() function have an option for this?
What would be the best way to pick a random number in a range of the form (x-1, x] given x?
I have done the following so far:
x=1
round(stats::runif(length(x), x-1, x), 2))
I just want to make sure to never obtain 0 here. Thanks!
Related
Consider this two‐dimensional random walk:
where, Zt, Wt, t = 1,2,3, … are independent and identically distributed standard normal
random variables.
I am having problems in finding a way to simulate and plot the sample path of (X,Y) for t = 0,1, … ,100. I was given a sample:
The following code is an example of the way I am used to plot random walks in R:
set.seed(13579)
r<-sample(c(-1,1),size=100,replace=T,prob=c(0.5,0.5))
r<-c(10,r))
(w<-cumsum(r))
w<-as.ts(w)
plot(w,main="random walk")
I am not very sure of how to achieve this.
The problem I am having is that this kind of codes has a more "simple" result, with a line that goes either up or down, -1 or +1:
while the plot I need to create also goes from left to right and viceversa.
Would you help me in correcting the code I know so that it fits my task/suggesting a smarterst way to go about it? It would be greatly appreciated.
Cheers!
Instead of using sample, you need to use rnorm(100) to draw 100 samples from a standard normal distribution. Since the walk starts at [0, 0], we need to append a 0 at the start and do a cumsum on the result, i.e. cumsum(c(0, rnorm(100))).
We want to do this for both the x and y variables, then plot. The whole thing can be done in a single line of code in base R:
plot(x = cumsum(c(0, rnorm(100))), y = cumsum(c(0, rnorm(100))), type = 'l')
I want to calculate the following integrate by using the hit and miss method.
I=∫x^3dx with lower= 0 and upper =1
I know how to solve it but I cannot find the right code in R to calculate it and generate -for example 100000 random- and then plot them like this:
Thank you.
1. Generate 2 vectors from uniform distribution of the desired length
l = 10000
x = runif(l)
y = runif(l)
2. The approximation of the integral is the number of cases where the (x,y) points are below the function you want to integrate:
sum(y<x^3)/l
3. For the plot, you just have to plot the points, changing their color depending whether they are above or below the curve, and add the function with curve():
plot(x,y,col=1+(y<x^3))
curve(x^3,add=T,col=3)
I am learning to plot histograms in R, but I have some problem with parameter "breaks" for a single number. In the help, it says:
breaks: a single number giving the number of cells for the histogram
I did the following experiment:
data("women")
hist(women$weight, breaks = 7)
I expect it should give me 7 bins, but the result is not what I expected! It gives me 10 bins.
Do you know, what does breaks = 7 mean? What does it mean in the help "number of cells"?
Reading carefully breaks argument help page to the end, it says:
breaks
one of:
a vector giving the breakpoints between histogram cells,
a function to compute the vector of breakpoints,
a single number giving the number of cells for the histogram,
a character string naming an algorithm to compute the number of cells (see ‘Details’),
a function to compute the number of cells.
In the last three cases the number is a suggestion only; the breakpoints will be set to pretty values. If breaks is a function, the
x vector is supplied to it as the only argument.
So, as you can notice, n is considered only a "suggestion", it probably tries to get near to that value but it depends on the input values and if they can be nicely split into n buckets (it uses function pretty to compute them).
Hence, the only way to force the number of breaks is to provide the vector of interval breakpoints between the cells.
e.g.
data("women")
n <- 7
minv <- min(women$weight)
maxv <- max(women$weight)
breaks <- c(minv, minv + cumsum(rep.int((maxv - minv) / n, n-1)), maxv)
hist(women$weight, breaks = breaks)
This should be simple for those with experience.
I want to solve an equation using R. I know you can solve
different linear/quadratic equations using Solve().
But I have something like this:
1/20 = 1/8 * (1/(12+x)) + 1/4*(1/(40+x)) + 3/4*(1/(50+x))
How can I solve x in this case? It can't be done by hand.
It gotta be some numeric methods involved to solve this like in TI83.
Is there a simple and quick way to do this in R without writing lines of codes?
Thank you!
As you say, there are indeed roots. First thing is to plot the function:
f <- function(x) {1/20 - 1/8 * (1/(12+x)) + 1/4*(1/(40+x)) + 3/4*(1/(50+x))}
x <- seq(-100,100)
par(mar=c(2,2,1,2)) # this just minimizes plot margins
plot(x,f(x), type="l")
abline(0,0,col="blue",lty=2)
So obviously, f(x) does cross 0, several times.
Next step is to estimate the crossings. One way to do this is to look for changes in sign:
x <- seq(-75,0,0.001)
y <- sign(f(x)) # vector of +1 or -1
plus.to.minus <- which(diff(y)<0) # diff(y)<0 when f crosses from (+) to (-)
minus.to.plus <- which(diff(y)>0) # diff(y)>0 when f crosses from (-) to (+)
# first two roots are (+) to (-); third is (-) to (+)
lower <- c(plus.to.minus[1:2],minus.to.plus[3])
roots <- sapply(lower,function(i)uniroot(f,interval=c(x[i],x[i+1]))$root)
lapply(roots,function(x) points(roots,c(0,0,0),col="red",pch=16))
roots
# [1] -67.38961 -41.72593 -10.38446
This code attempts to find x where f(x) changes sign. There are actually two reasons that f(x) could change sign: a root, or an asymptote. In your case there are three roots, and three asymptotes. Success here depends on having a small enough increment in x so that you don't completely miss a crossing. Based in the graph above it looks like 0.001 is small enough.
Here, y is a vector which contains the sign of f (as +1 or -1) at x between -75 and 0, in increments of 0.001. The limits (-75,0) were chosen by inspecting the plot above. We can see visually that there are three roots. The first two cross from (+) to (-), and the third crosses from (-) to (+). So we identify the index of x where the crossings occur (using which(...)), and then create a vector that contains the first two elements of plus.to.minus and the third element of minus.to.plus. Then we call uniroot(...) using increment=c(x[i],x[i+1]) where i is the index of the appropriate crossing.
Finally, we plot the results to confirm that we have in fact found the roots. This is really important - always, always plot the results. It turns out that uniroot(...) will find a "root" where there is an asymptote, so you have to make sure you've found actual roots.
Use uniroot() to solve equations in one variable:
f <- function(x){
1/8 * (1/(12+x)) + 1/4*(1/(40+x)) + 3/4*(1/(50+x)) - 1/20
}
uniroot(f, interval = c(-1e+08, 1e+08))
Notice that in the function, f, I subtract 1/20. This is because uniroot() finds the zero of the function.
In this case, you will get the error:
Error in uniroot(f, interval = c(-1e+08, 1e+08)) :
f() values at end points not of opposite sign
To correct this, you need to make sure the zero exists and if it does, move the interval, (a, b) so that f(a) == -f(b)
I have two approximated functions and I want to find the maximum value (error) between their graphs, to see how much they approach. I used :
FindMaximum[Abs[f[x] - p[x]], x], but Mathematica 8 gave me that output:
{2.75612*10^104, {x -> 2.75612*10^104}}
what does this mean? It is too big!
can you suggest me a better way?
Thanks
It's hard to tell not knowing your functions, but I'd guess that the position of the maximum it found is well outside your intended domain. You may have more success using a different form or FindMaximum, namely
FindMaximum[Abs[f[x] - p[x]],{x,x0,xmin,xmax}]
where x0 would be your initial guess for it (can be any point inside the region of interest), and xmin,xmax are the endpoints of your region of interest.
The reason is probably what Leonid said. To look at what FindMaximum is doing in real time, you can do
f[x_] := Sin[x];
p[x_] := x^2;
lst = {};
Monitor[
FindMaximum[Abs[f[x] - p[x]], x,
EvaluationMonitor :> (AppendTo[lst, x]; Pause[.01])
], ListPlot[lst, PlotRange -> Full]
]
the vertical axis on the resulting plot is the x-coordinate FindMaximum is currently looking at. Once FindMaximum is done, the plot disappears; the list is stored in lst so you can eg ListPlot it.
You can also try this with {Abs[f[x] - p[x]], -1 <= x <= 1} as the argument, as suggested by Spencer Nelson, to see how the search proceeds then.
This is probably caused by some sort of overflow in one of the two functions when the input value of x is a very large number. You should restrict your domain to [-1, 1]:
FindMaximum[{Abs[f[x] - p[x]], -1 <= x <= 1}, x]
If you want to search for a global maximum within the interval {a, b}, I suggest NMaximize:
NMaximize[{Abs[f[x] - p[x]], a <= x <= b}, x].
Note that FindMaximum searches for any local maximum, which is only good if you know that, for your particular function, a local maximum would also be a global maximum.
Instead of the objective function Abs[f[x] - p[x]], you may wish to use the objective function (f[x] - p[x])^2. This would make the objective function smooth (if f[x] and p[x] are smooth), which can help improve the efficiency of some numerical optimization methods.