简体   繁体   English

用于替换 R 中值的自定义函数

[英]Custom function to replace values in R

I'm trying to create a function to replace outliers in a variable:我正在尝试创建一个函数来替换变量中的异常值:

outlier_upper_replace <- function(x, level=1.5) {
  lowerq = quantile(x, na.rm=TRUE)[2]
  upperq = quantile(x, na.rm=TRUE)[4]
  iqr = upperq - lowerq
  outlier_upper = (iqr * level) + upperq
  x[x > outlier_upper] <- outlier_upper
}

I can't understand why outlier_upper_replace(prod$varname) is not replacing the value.我不明白为什么outlier_upper_replace(prod$varname)没有替换该值。

If I run the following code, which is a particular case of the above function, the value is replaced:如果我运行以下代码,这是上述函数的一个特例,该值将被替换:

level = 1.5
lowerq = quantile(prod$varname, na.rm=TRUE)[2]
upperq = quantile(prod$varname, na.rm=TRUE)[4]
iqr = upperq - lowerq
outlier_upper = (iqr * level) + upperq
prod$varname[prod$varname > outlier_upper] <- outlier_upper

Any insights about why this is happening?关于为什么会发生这种情况的任何见解?

EDIT: Example编辑:示例

set.seed(1)
x <- rnorm(100)
x <- c(-10, x, 10)

boxplot(x, main="start boxplot")

#function to bin-in upper outliers
outlier_upper_replace <- function(x, level=1.5) {
  lowerq = quantile(x, na.rm=TRUE)[2]
  upperq = quantile(x, na.rm=TRUE)[4]
  iqr = upperq - lowerq
  outlier_upper = (iqr * level) + upperq
  x[x > outlier_upper] <- outlier_upper
  return(x)
}

outlier_upper_replace(x)

boxplot(x, main="end boxplot")

Add添加

return(x)

to the end of your function.到你的函数结束。

The return value of an R function is the result of the last expression in the function body. R 函数的返回值是函数体中最后一个表达式的结果。 Since you modify the vector in the last expression there is no result and you have to explicitly return the result.由于您修改了最后一个表达式中的向量,因此没有结果,您必须明确返回结果。

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

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