# Write a function to calculate the PDF in R?

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?

## Answers

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.