mercredi 4 septembre 2019

How to restrict a function to only a fraction of the input variable range in R?

I am trying to construct a function that runs on the variable y, but only if it's value is less than 1. In case it counters a value more than 1, it simply does nothing. I can't have it returning NaNs since I need to perform some numerical operation on the output later on and if NaNs or any 'non-existent' value is returned I can't do that.

I have tried using stopifnot but of course that returns an error. I have tried using ifelse statements, but I don't know what to put in the 'else' side of things, for example if I put "next" it simply says that no loop for break/next which makes sense. I want the function to just not take in the value if they are not less than 1.

#Some base functions to build up to the function I want
s <- function(x,y){(1/y)*exp(-(1/y)*(x-1+y))}
p <- function(x) (1/x)
s1 <- function(x,y){s(p(x),y)*((p(x))^(3))}
logs1 <- function(x,y){3*log(p(x))-log(y)-(1/y)*(p(x)-1+y)}
s2 <- function(x,y) s(x,y)*logs1(p(x),y)

Now I want to integrate s2 with respect to x, from 0 to (1/(1-y)) The values of y=[0.2,2], it has to be upto 2 because I am using the same y for a few functions, however here it's clear that the value of y can not be equal to or more than 1, so how do I make sure that the output that the function below gives is only for y less than 1?

s3 <- function(y){
if (y < 1)
-(integrate(s2, lower=0, upper=(1/(1-y)), y=y)$value)  
else
    next
}

My last function is KL_s(y), which is attained this way:

h.s <- Vectorize(s3)
KL_s <- function(y) 1-h.s(y)

I need the s3 to be defined in a way that putting this value of y:

y <- seq(0.2,2.0,0.01)

gives me return values of KL_s(y) but only for y < 1, after that I am plotting KL_s(y) with some of the similar function (that's why the range has to be uniform from 0.2 to 2 for all of them, so plotting is easier). Please help me see how I can go around it. I am quite new to coding so the intuition doesn't come easy.

Aucun commentaire:

Enregistrer un commentaire