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.


Need Your Help

Matlab work with each vector from a 4D array

arrays image matlab image-processing

I have a 4D matrix of size, let's say, 100x200x3x10 where 100x200 is the size of one image, 3 is the number of channels (RGB images) and 10 is the number of images.

Python/Django: Can a process keep running after the user sees the “Thanks. You're done!” page

python django multithreading

I'm trying to understand threading better. If I create a program that allows people to upload a photo and then I create a new process to resize the image in a hundred ways (taking 5 seconds or long...

About UNIX Resources Network

Original, collect and organize Developers related documents, information and materials, contains jQuery, Html, CSS, MySQL, .NET, ASP.NET, SQL, objective-c, iPhone, Ruby on Rails, C, SQL Server, Ruby, Arrays, Regex, ASP.NET MVC, WPF, XML, Ajax, DataBase, and so on.