【问题标题】:R Function errorR 函数错误
【发布时间】:2015-10-23 09:55:35
【问题描述】:

我有一个包含 17 个变量的数据集,它们都是整数/数字。 为了更好的描述性分析,我创建了这个用户定义的函数:

 sum <- function(x)
  {
    na.len<-sum(is.na(x))
    mean<-mean(x,na.rm=T)
    sd<-sd(x,na.rm=T)
    min<-min(x,na.rm=T)
    q1<-quantile(x,0.25,na.rm=T)
    q3<-quantile(x,0.75,na.rm=T)
    max<-max(x,na.rm=T)
    UC1=mean+3*sd
    LC1=mean-3*sd
    UC2=quantile(x,0.99,na.rm=T)
    LC2=quantile(x,0.01,na.rm=T)
    iqr=IQR(x,na.rm=T)
    UC3=q3+1.5*iqr
    LC3=q1-1.5*iqr
    ot<-max>UC1 | min<LC1 | max>UC2 | min<LC2 | max>UC3 | min<LC3
    x[x>max]<-max
    x[x<min]<-min
    out_exist <- ifelse(noofNA > 0, "outlier_exists", "")
    return(c(noofNA=na.len,mean=mean,std=sd,min=min,q1=q1,q3=q3,max=max,outlier=ot, out_exists= out_exist))
  }

当我在我的数据集上使用这个函数时:

apply(df, 2, sum)

我收到以下错误:

错误:评估嵌套太深:无限递归 / 选项(表达式=)?总结期间出错:评估也嵌套 深度:无限递归/选项(表达式=)?

我试图了解问题所在,但徒劳无功,请帮助!

【问题讨论】:

  • 如果你问为什么这段代码不起作用,它应该包含在一个最小的可重现示例中。我还建议将功能拆分为小部分,然后找到它不工作的地方。
  • 您将函数命名为sum,然后在其中调用函数sum 来执行求和。更改函数的名称。
  • 另外,不要这样做mean&lt;-mean(x,na.rm=T),而不是命名结果mean尝试使用这样的东西:meanResult &lt;- mean(x, na.rm = TRUE)
  • 证明:sum &lt;- function(x){ sum(x) }; sum(1)Error: evaluation nested too deeply: infinite recursion / options(expressions=)?
  • 我更新了函数:

标签: r function user-defined-functions


【解决方案1】:

你的函数应该是这样的。但是你没有定义noofNA,所以还是会报错。

details <- function(x)
{
  na.len <- sum(is.na(x))
  m <- mean(x, na.rm=TRUE)
  s <- sd(x, na.rm=TRUE)
  mn <- min(x, na.rm=TRUE)
  q1 <- quantile(x, 0.25, na.rm=TRUE)
  q3 <- quantile(x, 0.75, na.rm=TRUE)
  mx <- max(x, na.rm=TRUE)
  UC1 <- m+3*s
  LC1 <- m-3*s
  UC2 <- quantile(x, 0.99, na.rm=TRUE)
  LC2 <- quantile(x, 0.01, na.rm=TRUE)
  iqr <- IQR(x, na.rm=TRUE)
  UC3 <- q3+1.5*iqr
  LC3 <- q1-1.5*iqr
  ot <- mx>UC1 | mn<LC1 | mx>UC2 | mn<LC2 | mx>UC3 | mn<LC3
  x[x>mx]<-mx
  x[x<mn]<-mn
  out_exist <- ifelse(noofNA > 0, "outlier_exists", "")
  return(list(noofNA=na.len, mean=m, std=s, min=mn, q1=q1, q3=q3, max=mx, outlier=ot, out_exists= out_exist))
}

set.seed(123)
df1 <- data.frame(x = rnorm(100), y = rnorm(100))
sapply(df1, details)

【讨论】:

    猜你喜欢
    • 2012-08-25
    • 2013-02-24
    • 1970-01-01
    • 2020-02-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多