[英]Any help appreciated. R: Creating function that calculates sqrt of x, if x is negative return Na
Create a function that, given a numeric value x, calculates the square root of x.创建一个函数,给定一个数值 x,计算 x 的平方根。 If the value contained in x is negative it should return NA.如果 x 中包含的值为负,则应返回 NA。
One possibility would be:一种可能性是:
fun <- function(x) x^.5
fun(3)
# [1] 1.732051
fun(-1)
# [1] NaN
If NA
needed instead of NaN
, use an ifelse
.如果需要NA
而不是NaN
,请使用ifelse
。
fun2 <- function(x) ifelse(x < 0, NA, x^.5)
fun2(-1)
# [1] NA
fun2(3)
# [1] 1.732051
fun2(c(-1, 3))
# [1] NA 1.732051
You can try ifelse
to define your vectorized custom function f
, eg,您可以尝试ifelse
来定义您的矢量化自定义函数f
,例如,
f <- Vectorize(function(x) ifelse(x>=0,sqrt(x),NA))
or或者
f <- function(x) suppressWarnings(ifelse(x>=0,sqrt(x),NA))
Example例子
> f(c(-1,0,1,2,3))
[1] NA 0.000000 1.000000 1.414214 1.732051
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.