Search code examples
rdistributionpoisson

Error : Non-numeric argument to mathematical function in R


dbl_var<-lambda
probpois <-function(x,  lambda){

  #e<-2.718
prob<-exp(((lambda^x)*(2.718^lambda))/factorial(x))

retun(prob)

}

a<-readline((prompt="Enter a value: "))
b<-readline((prompt="Enter b value: "))
lambda<-readline((prompt="Enter lambda value: "))
x<-(a:b)
while (x<b || x>a ) {

dpois(x ,lambda)

}

ı want to write calculate poisson distribution program in R studio. This program will an error. >> "Error in dpois(x, lambda) : Non-numeric argument to mathematical function"

Console:

  > dbl_var<-lambda
> probpois <-function(x,  lambda){
+   
+       #e<-2.718
+  prob<-exp(((lambda^x)*(2.718^lambda))/factorial(x))
+   
+   retun(prob)
+ 
+ 
+ 
+ }
> a<-readline((prompt="Enter a value: "))
Enter a value: 1
> b<-readline((prompt="Enter b value: "))
Enter b value: 4
> lambda<-readline((prompt="Enter lambda value: "))
Enter lambda value: 1.5
> x<-(a:b)
> while (x<b || x>a ) {
+ 
+ dpois(x ,lambda)
+   
+ }
Error in dpois(x, lambda) : Non-numeric argument to mathematical function
> 

Solution

  • readline always returns whatever the user types as character data. Wrap your readline statements in as.numeric, like so:

    a <- as.numeric(readline(prompt="Enter a value: "))
    

    In addition, I'm not entirely sure of your goal here, but the while loop is being used incorrectly. In fact it seems entirely unnecessary, since dpois can simply be given the four values you've calculated for x.