简体   繁体   English

R 中的分段函数帮助

[英]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.我已经尝试了 ifelse 序列,但我似乎无法让它工作。 I've also tried an if, elseif, else sequence, but that only seems to use the first function to calculate answers.我也尝试过 if、elseif、else 序列,但这似乎只使用第一个函数来计算答案。 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:上面对 ThomasIsCoding 的回答的编辑给了你你想要的,但我会使用这种方法,因为它更好地传达了它的意图:

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:并得到:

在此处输入图片说明

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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