简体   繁体   中英

Piecewise Function Help in R

For a class I must create a piecewise function defined in the following way:

2x-2   , x < -1
0      , -1 <= X <= 1
x^(2)-1, x > 1

I have tried an ifelse sequence but I cant seem to make it work. I've also tried an if, elseif, else sequence, but that only seems to use the first function to calculate answers. The end goal is to have this:

    pwfun(c(-2, 0.5, 3))
    2 0 8

A piece-wise function like below?

pwfun <- function(x) ifelse(x < -1, 2 * x - 2, ifelse(x <= 1, 0, x**2 - 1))

such that

> pwfun(c(-2, 0.5, 3))
[1] -6  0  8
pwfun <- function(x) ifelse(x < -1, (x * x) -2, ifelse(x <= 1, 0, x**2 - 1))


> pwfun(c(-2, 0.5, 3))
[1] -2  0  8

The above edit to ThomasIsCoding's answer gives you what you want, but I would use this approach because it communicates it's intent better:

library(dplyr)

df <- data.frame(x = c(-2, 0.5, 3))

pwfunc <- function(data){
    data %>%
        mutate(y = 
            case_when(x < -1 ~ -2,
                      x > 0 & x <= 1 ~ 0,
                      TRUE ~ x**2 - 1)) ## TRUE in a case_when basically
                                        ## means "everything that isnt caught by my specified conditions
                                        ## becomes..." so it works like the "else" clause
}

Then just call the function on your data:

df <- data.frame(x = c(-2, 0.5, 3))

pwfunc(data)

And get:

在此处输入图片说明

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM