用 R 向量化我的函数不起作用 [英] Vectorize my function with R is not working

查看:32
本文介绍了用 R 向量化我的函数不起作用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有这个功能:

fx <- function (x) {
  if (x <= 0) {
    return(-1 * (x**3))
  }
  else if (0 < x && x <= 1) {
    return(x**2)
  }
  else if (x > 1) {
    return(sqrt(x))
  }
}

我转换为向量化函数:

fVectorize <- function(x) {
  result <- ifelse(x <= 0, -1 * (x**3), ifelse(0 < x && x <= 1, x**2, sqrt(x)))
  result
}

我尝试了以下值但不起作用:

I tried the following values but doesn't work:

fVectorize(c(-2, -4, -5))
fVectorize(c(0.5, 0.3, 0.7))
fVectorize(c(3, -4, 0.7))

似乎只采用第一个条件.

Seems like is only taking the first condition.

有什么想法吗?

推荐答案

&& 更改为 &

fVectorize <- function(x) {
  result <- ifelse(x <= 0, -1 * (x**3), ifelse(0 < x & x <= 1, x**2, sqrt(x)))
  result
}
fVectorize(c(-2, -4, -5))
#[1]   8  64 125

fVectorize(c(0.5, 0.3, 0.7))
#[1] 0.25 0.09 0.49

fVectorize(c(3, -4, 0.7))
# [1]  1.732051 64.000000  0.490000

& 执行元素明智的操作,其中 as && 查找第一个返回值的元素.

& does element wise operation where as && looks the first element to return a value.

这篇关于用 R 向量化我的函数不起作用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆