问题
I'm to write a function to calculate the PDF of and it's been suggested that I use the if/elseif/else statements. However whenever I try and do so, I keep getting error messages but I'm not sure what I'm doing wrong?
This is the PDF that the function is supposed to calculate:
fx = 0.3 if (0<=x<1)
0.1 if (1<=x<2)
0.25 if (2<=x<3)
0.15 if (3<=x<4)
0.2 if (4<=x<5)
0 otherwise
This is my code:
fx = function(x)
{
if (0<=x<1) {
pdf=0.3
} elseif (1<=x<2) {
pdf=0.1
} elseif (2<=x<3) {
pdf=0.25
} elseif (3<=x<4) {
pdf=0.15
} elseif (4<=x<5) {
pdf=0.2
} else
pdf=0
pdf
}
I have checked my '}' but they all seem appropriately placed. I've tried changing 'pdf' to 'fx' but that doesn't work. Where am I going wrong?
回答1:
fx <- function(x) c(0, 0.3,0.1,0.25,0.15,0.20, 0)[findInterval(x, c(-Inf, 0:5, Inf))]
The findInterval
function returns the position of its first argument from within a sequence of intervals defined by its second argument and can be used to select a probability from a vector. The values outside the domain of support get chosen as 0 values as requested. It is particularly useful in cases like this where the lower bounds are closed, since the default for the cut
function is to have upper bounds as closed.
回答2:
there were two problems with your code
1/ Expressions such as a <= x < b are legal in maths but not in code. In code you need a <=x && x < b
2/ You need to use "else if" rather than "elseif"
This code works
fx = function(x)
{
if (0<=x && x<1) {
pdf=0.3
} else if (1<=x && x<2) {
pdf=0.1
} else if (2<= x&& x<3) {
pdf=0.25
} else if (3<=x && x<4) {
pdf=0.15
} else if (4<= x&& x<5) {
pdf=0.2
} else
pdf=0
pdf
}
Also, as an optimization, you should only repeatedly need to test that x < b, not the a. And you shouldn't need a pdf variable. This leads to the following code, but I'm guessing that the built-in function that was posted above is more efficient.
fx = function(x)
{
if (x<0) 0
else if (x<1) 0.3
else if (x<2) 0.1
else if (x<3) 0.25
else if (x<4) 0.15
else if (x<5) 0.2
else 0
}
回答3:
You could use stepfun
to create a step function (which is what your PDF is)
fx <- stepfun(x = 0:5, y = c(0,0.3,0.1,0.25,0.15,0.20,0))
If you want a vectorized version, then you can use Vectorize
vfx <- Vectorize(fx)
stepfun
objects can be plotted nicely using plot
(see https://stackoverflow.com/a/16072697/1385941 for a related example)
来源:https://stackoverflow.com/questions/16070405/write-a-function-to-calculate-the-pdf-in-r