[R] ifelse and piecewise function
David Winsemius
dwinsemius at comcast.net
Sat Jan 2 02:31:36 CET 2010
On Jan 1, 2010, at 7:44 PM, roger king wrote:
> I am a novice user of "R" and I'm learning with R version 2.8.1,
> using
> WinEdt_1.8.1, under Widows Vista Home Version.
>
> ## The test function below, from a vector input, returns vector
> values:
> # and it contains an "ifelse"statement
> TEST<- function(x) {
> low<- -x^2
> up<- x^4
> ifelse(x>=0,up,low )
> }
> u<- seq(-1,1,0.5)
> TEST(u)
> ###########################################################
> # #The following function, also containing "ifelse", returns correct
> individual values
> # (confirmed independently from another program).
> # Vector input, however, generates the following message:
> # "In if (is.finite(lower)) { :the condition has length > 1 and
> only the
> first element
> # will be used"
> # And, in fact, correct multiple values are not returned.
> ########################################################
> ASEPF<- function(y, theta, sigma, alpha, kappa){
>
> loww<-((theta - y)/(sigma* kappa))^alpha
>
> upp<- (kappa *(y - theta)/sigma)^alpha
>
> k<- 1/(1 + kappa^2)
>
> a<- 1/alpha
>
> integrand<- function(y){y^(a-1)* exp(-y)/gamma(1/alpha)}
>
> GL<- integrate(integrand, lower = loww, upper= Inf)$value
>
> GU<- integrate(integrand, lower = upp, upper= Inf)$value
> ifelse(y>=0,1 - k*GU, (kappa^2) *k * GL)
> }
> ASEPF(u,0,1,2,0.5)
> Could someone kindly give me some advice on how to
> rewrite the function ASEPF so that it returns a vector of values?
But, but, but, ... it did return a vector of values. You failed to
recognize them:
ASEPF(u,0,1,2,0.5)
[1] 0.000935539 0.000935539 0.616399902 0.616399902 0.616399902
The above line is the vector of values that you did not post.
Then you also got.....
Warning messages:
1: In if (is.finite(lower)) { :
the condition has length > 1 and only the first element will be used
2: In if (is.finite(lower)) { :
the condition has length > 1 and only the first element will be used
You need to figure out why your invocation of integrate is causing
complaints (only warnings, mind you) from the R interpreter, but the
problem is not with any failure to return a vector.
--
David.
>
> many thanks,
>
> Rik King
>
> rking681 at gmail.com
>
> (ex Mathematics Department,
> University of Western Sydney, Australia)
>
> [[alternative HTML version deleted]]
>
> ______________________________________________
> R-help at r-project.org mailing list
> https://stat.ethz.ch/mailman/listinfo/r-help
> PLEASE do read the posting guide http://www.R-project.org/posting-guide.html
> and provide commented, minimal, self-contained, reproducible code.
David Winsemius, MD
Heritage Laboratories
West Hartford, CT
More information about the R-help
mailing list