Error : Non-numeric argument to mathematical function in R - 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
>

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.

Related

Why am I getting a "non-numeric argument to binary operator" when trying to apply a function in R

Here is a ficticious dataset consisting of 10 genetic lines and a set of 7 parameters:
data.1<-read.csv(text="
line,a,b,c,d,TF1,TF2,TF3
line1,0.716954406,0.948933475,0.723180846,0.122529549,-1,-1,-1
line2,0.443478142,0.052760906,0.814897888,0.072935389,1,-1,1
line3,0.362944986,0.892056197,0.243860823,0.197642553,1,1,1
line4,0.516451924,0.742629204,0.170810671,0.886592564,-1,-1,-1
line5,0.262766818,0.676690503,0.585481859,0.544782573,1,1,1
line6,0.437307171,0.326012372,0.194698638,0.992025701,1,1,1
line7,0.018027541,0.241761164,0.068979207,0.170437435,1,-1,1
line8,0.663364588,0.237946201,0.056954659,0.953926657,1,1,1
line9,0.062131129,0.066129381,0.156008808,0.235503941,-1,-1,-1
line10,0.018027541,0.241761164,0.06897920,0.170437435,-1,-1,-1
")
What I am trying to do is to apply the folowing function to each line and get a sim value:
flow.function <- function(a, b, c, d, TF1, TF2, TF3) {
sim <- 44.18 + 4.026*(a-12.7) + 0.195*(b-18.21) - 1.363*(c-27.4) - 0.60*(d-16.12) - 1.3*TF1 - 2.279*TF2 + 1.59*TF3
return(sim)
}
Then I apply the function row wise:
data.1$sim.results <- apply(data.1, 1, flow.function)
And this is the error I am getting:
Error in a - 12.7 : non-numeric argument to binary operator
I undertand the error is pointing out to the "12.7" value in the formula, what I have no idea why I get this error since 12.7 is a number. I am surely missing something basic.
Any help will be really appreciated.
Because you did not provide additional function arguments in apply (it only expects one function argument). Try the following:
data.1<-read.csv(text="
line,a,b,c,d,TF1,TF2,TF3
line1,0.716954406,0.948933475,0.723180846,0.122529549,-1,-1,-1
line2,0.443478142,0.052760906,0.814897888,0.072935389,1,-1,1
line3,0.362944986,0.892056197,0.243860823,0.197642553,1,1,1
line4,0.516451924,0.742629204,0.170810671,0.886592564,-1,-1,-1
line5,0.262766818,0.676690503,0.585481859,0.544782573,1,1,1
line6,0.437307171,0.326012372,0.194698638,0.992025701,1,1,1
line7,0.018027541,0.241761164,0.068979207,0.170437435,1,-1,1
line8,0.663364588,0.237946201,0.056954659,0.953926657,1,1,1
line9,0.062131129,0.066129381,0.156008808,0.235503941,-1,-1,-1
line10,0.018027541,0.241761164,0.06897920,0.170437435,-1,-1,-1
")
flow.function <- function(a, b, c, d, TF1, TF2, TF3) {
sim <- 44.18 + 4.026*(a-12.7) + 0.195*(b-18.21) - 1.363*(c-27.4) - 0.60*(d-16.12) - 1.3*TF1 - 2.279*TF2 + 1.59*TF3
return(sim)
}
data.1$sim.results <- mapply(flow.function, data.1$a, data.1$b, data.1$c, data.1$d, data.1$TF1, data.1$TF2, data.1$TF3)

Specify the calling function for an error message in R

I'm working on an R package where the same input-checking functions are called by multiple "actual" functions that are exported to users. If I use a simple stop() call, the error message is going to say that an error occurred in the input-checking function, which is not that useful...
I thought I'd get around this by wrapping the call to the input-checking function inside a tryCatch(), and then handling the error in the outer function. This does mostly what I want, but doesn't quite give the output that I'd like. The closest I've come is the following:
f <- function(i) {
tryCatch({
check_input(i)
}, error = function(e) stop("in f: ", e$message, call. = FALSE)
)
}
check_input <- function(i) {
if(i < 0)
stop("i is negative, value given was ", i)
}
f(-1)
# Error: in f: i is negative, value given was -1
Ideally, I'd like the error message to be
Error in f: i is negative, value given was -1
, which would be the case if stop were called within f() instead of check_input().
Here's how you can grab the name of the function from the call stack and paste it in to the error message
f <- function(i) {
check_input(i)
}
g <- function(i) {
check_input(i)
}
check_input <- function(i, from=deparse(sys.calls()[[sys.nframe()-1]][[1]])) {
getmsg <- function(m) ifelse(!is.null(from), paste0("in ", from, ": ", m), m)
if(i < 0)
stop(getmsg(paste0("i is negative, value given was ", i)), call. = FALSE)
}
f(-1)
# Error: in f: i is negative, value given was -1
g(-1)
# Error: in g: i is negative, value given was -1
You could also call check_input(i, from="otherfunction") to show whatever function name you want or check_input(i, from=NULL) to suppress the function name.

GARCH models testing in R

I would to take five parametrs: a, b, c, d and mean of standards deviation from every model (it is a normal value, no matrix) and store this information as a vector, then using rbind to crate matrix which I can search for the models and parameters.
I was trying with nested loops like:
for (a in 0:2){
for (b in 0:2){
for (c in 1:2){
for (d in 1:2){
Garch_model <- garchFit(~arma(a,b)+garch(c,d), include.mean = TRUE,cond.dist = c("norm"),data = dax_data)
ValidationBox <- rbind(ValidationBox,c(a,b,c,d,mean(Garch_model#sigma.t))
}
}
}
}
but I'm getting this error:
Error: unexpected '}' in: " ValidationBox <-
rbind(ValidationBox,c(a,b,c,d,mean(Garch_model#sigma.t))
}"
} Error: unexpected '}' in " }"
} Error: unexpected '}' in " }"
} Error: unexpected '}' in "}"
Can anyone tell me what's the issue?

How to detect numbers from one column in another and write data from another column in R?

I'm very new at R language. I tried to make simple code to find some data in different intervals with information about start-end of interval and table with bigger intervals for now, I got several codes for solving but none of them work.
The main idea is that I have several variables which represent different arrays (i,k,j). Code, in my opinion, should look for each array in another table for two things (if it bigger than the first column and if it smaller then second, if both true - right all this to another table and go to other intervals).
if(mydatatable[k,21]>=mydatatable[i,16]){
if(mydatatable[k,21]<=mydatatable[j,18])
shifr[n,1]<-n&shifr[n,2]<-mydata[k,21]&shifr[n,3]<-mydata[k,22]&i+1&j+1&k+1&n+1
else i+1&j+1&k+1
}
else {
if(mydatatable[i,16]==0) end
else i+1&j+1&k+1
}
for this code several errors
Error in if (mydatatable[k, 21] >= mydatatable[i, 16]) { :
missing value where TRUE/FALSE needed
In addition: Warning message:
In Ops.factor(mydatatable[k, 21], mydatatable[i, 16]) :
‘>=’ not meaningful for factors
I wonder, why programm thinks, that mydatatable is factor? Why it should be some TRUE/FALSE value, I thought, that it was already established in formula.
The second code is pretty much the same and it even might work.
I preestablished the values i,k and j as 1 (i=1, k=1, j=1)
But there comes a error
> ifelse(mydatatable[k,21]>=mydatatable[i,16],
+ ifelse(mydatatable[k,21]<=mydatatable[j,18],
+ shifr[n,1]<-n&shifr[n,2]<-mydata[k,21]&shifr[n,3]<-mydata[k,22]&i+1&j+1&k+1&n+1,i+1&j+1&k+1),
+ ifelse(mydatatable[i,16]==0,
+ end),
+ i+1&j+1&k+1)
Error in ifelse(mydatatable[k, 21] >= mydatatable[i, 16], ifelse(mydatatable[k, :
unused argument (i + 1 & j + 1 & k + 1)
I'm confused, why it's happening.
Please, help.
Here is an example of data. What I want to get is demonstrated here https://1drv.ms/f/s!Aj4W4aYSeYkGiIFKHG0TV-TRQvWaIQ
Here what I got, after several use of data.table::foverlaps (I fixed some problems, but initially I got this)
> data.table::foverlaps(int1,sh2,by.x=c("start","end"),by.y=c("start","end"))
Error in data.table::foverlaps(int1, sh2, by.x = c("start", "end"), by.y = c("start", :
The first 2 columns of y's key is not identical to the columns specified in by.y.
I have also got some progress with previous code. Several problems: first, how to unite several commands (I used & and ; but none of them worked properly in shifr[n,1]<-n;shifr[n,2]<-sh[k,1];shifr[n,3]<-sh[k,1];i+1&j+?)
Second, is about Error in FUN(left, right).
> ifelse(sh[k,1]>=int[i,1],
+ + ifelse(sh[k,2]<=int[j,2],
+ + shifr[n,1]<-n;shifr[n,2]<-sh[k,1];shifr[n,3]<-sh[k,1];i+1;j+1;k+1;n+1,i+1;j+1;k+1),
Error: unexpected ';' in:
" + ifelse(sh[k,2]<=int[j,2],
+ shifr[n,1]<-n;"
> + i+1;j+1;k+1
[1] 16
[1] 16
[1] 65
> ifelse(sh[k,1]>=int[i,1],
+ + ifelse(sh[k,2]<=int[j,2],
+ + shifr[n,1]<-n;shifr[n,2]<-sh[k,1];shifr[n,3]<-sh[k,1];i+1&j+1&k+1&n+1,i+1&j+1&k+1),
Error: unexpected ';' in:
" + ifelse(sh[k,2]<=int[j,2],
+ shifr[n,1]<-n;"
> + i+1&j+1&k+1
[1] TRUE
> ifelse(sh[k,1]>=int[i,1],
+ + ifelse(sh[k,2]<=int[j,2],
+ + shifr[n,1]<-n&shifr[n,2]<-sh[k,1]&shifr[n,3]<-sh[k,1]&i+1&j+1&k+1&n+1,i+1&j+1&k+1),
+ + i+1&j+1&k+1
+ )
Error in FUN(left, right) :
operations are possible only for numeric, logical or complex types
This code is, actually, awful. I eventually done it like that(in python):
for i in interval:
...
if float(i) < intervals[b][0]:
print("Interval are too high", intervals[b][1])
break
....
if float(i) >= intervals[b - 1][1]:
....

R continue loop on error

apparently try and trycatch do not work for this problem! Any alternative solutions?
i'm trying to make the following example code work without actually changing any code
result = 0
for(i in 1:10){
result = result + i
log("a") #I do not care about this error
result = result + i
}
This should give result = 110
If i actually do it manually by copying the part inside the loop and increasing the counter it works perfectly:
result = 0
#iteration 1
i = 1
result = result + i
log("a")
result = result + i
#iteration 2
i = i+1
result = result + i
log("a")
result = result + i
#iteration 3
i = i+1
result = result + i
log("a")
result = result + i
#etc.
However my real code has about 1000 lines and needs to loop a few hundred times.
So i'd like to have some option
options(on.error.just.continue.the.next.line) = TRUE
I've read about try/tryCatch but I don't understand it correctly I think
If you just want the code to run, you can use try instead:
result <- 0
for(i in 1:10){
result = result + i
try({log("a")}) #I do not care about this error
result = result + i
}
Error in log("a") : non-numeric argument to mathematical function
Error in log("a") : non-numeric argument to mathematical function
Error in log("a") : non-numeric argument to mathematical function
Error in log("a") : non-numeric argument to mathematical function
Error in log("a") : non-numeric argument to mathematical function
Error in log("a") : non-numeric argument to mathematical function
Error in log("a") : non-numeric argument to mathematical function
Error in log("a") : non-numeric argument to mathematical function
Error in log("a") : non-numeric argument to mathematical function
Error in log("a") : non-numeric argument to mathematical function
result
[1] 110
To turn off the message, use
try({log("a")}, silent=TRUE)
If you are worried about a larger block of code, you can wrap it in { } as follows:
result <- 0
for(i in 1:10){
try({ # start code block
result = result + i
log("a") # I do not care about this error
result = result + i
}, silent=TRUE) # end of try function
}
result
[1] 55
Here, the first assignment to result completes in the for loop. Then the error occurs which "wipes out" the execution of the rest of the code block, which is the second assignment here. However, the loop execution is allowed to continue through completion.
You can try using a try catch block:
result = 0
for (i in 1:10) {
result = result + i
tryCatch({
log("a") #I do not care about this error
}, warning = function(w) {
# comment out the next print statement for a silent warning
print("warning")
}, error = function(e) {
# comment out the next print statement for a silent error
print("error")
}, finally = {
# cleanup
}
result = result + i
}

Resources