Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/r/64.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
R中函数的矢量化编码方法_R - Fatal编程技术网

R中函数的矢量化编码方法

R中函数的矢量化编码方法,r,R,如果我想编写一个数学函数: f(x) = 12 for x>1 = x^2 otherwise 如果我使用 mathfn<-function(x) { if(x>1) { return(12) } else { return(x^2) } } 有什么更健壮、矢量化的习惯用法来编码x,从而使x可以是标量或矢量?是否需要这样做: mathfn <- function(x)

如果我想编写一个数学函数:

f(x)
     = 12 for x>1
     = x^2 otherwise
如果我使用

mathfn<-function(x)
{
    if(x>1)
    {
        return(12)
    }
    else
    {
        return(x^2)
    }
}

有什么更健壮、矢量化的习惯用法来编码x,从而使x可以是标量或矢量?

是否需要这样做:

mathfn <- function(x) ifelse(x > 1, 12, x^2)
mathfn 1,12,x^2)

在第一种情况下是否需要将所有矢量元素更改为12?如果使用
ifelse
功能获得了矢量化的if else条件。
mathfn <- function(x) ifelse(x > 1, 12, x^2)