简体   繁体   English

任何帮助表示赞赏。 R:创建计算 x 的 sqrt 的函数,如果 x 为负返回 Na

[英]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.

相关问题 R中的逻辑表达式,是什么使is.na(x)返回NA - logical expressions in R, what makes is.na(x) return NA 牛顿求根函数不适用于 R 中的 sqrt(x) - Newton root finding function does not work with sqrt(x) in R 如何制作一个函数来计算 R 中 f(x) = exp(x) 的牛顿商? - How to make a function that calculates newtons quotient for f(x) = exp(x) in R? R for循环给出:if(is.na(x))return(0)else return(sign(x))中的错误:参数长度为零 - R for loop gives: Error in if (is.na(x)) return(0) else return(sign(x)) : argument is of length zero 警告消息 couldBeLonLat(x): CRS is NA using crop function in R - Warning message couldBeLonLat(x) : CRS is NA using crop function in R 在R中使用sqrt(x)和x ^ 0.5时结果不同 - Different result when using sqrt(x) and x^0.5 in R 如何使用for循环(在R中)运行函数(x),如果它返回NA,用函数(y)的输出替换NA? - How to use for-loop (in R) to run function(x) and if it returns NA, replace NA by output of function(y)? 在R中创建一个函数,然后对x进行y回归 - Creating a function in R, then regressing y on x 如何处理 R 中 lm(x~y) 函数中的负值? - How to treat negative values in lm(x~y) function in R? 当我们在 R 中计算 ARIMA 模型时,如何解决标准误差、z 和 pr 值的 NA 值? 在 sqrt(diag(x$var.coef)) 中:产生 NaN - How to solve NA values for standard errors, z and pr values when we are calculation ARIMA model in R? In sqrt(diag(x$var.coef)) : NaNs produced
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM