R函数误差

R函数误差,r,function,user-defined-functions,R,Function,User Defined Functions,我有一个包含17个变量的数据集,它们都是整数/num。 为了更好地进行描述性分析,我创建了此用户定义函数: 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

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

 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))
  }
我发现以下错误:

错误:计算嵌套太深:无限递归/ 选项(表达式=)?wrapup期间出错:计算也嵌套 深度:无限递归/选项(表达式=)


我试图了解问题所在,但都是徒劳的,请帮助

您的函数应该是这样的。但是您没有定义
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)

details这是函数的外观。但是您没有定义
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)

详细信息如果您询问为什么此代码不起作用,则应将其包含在最小可复制示例中。我还建议将函数分成几个小部分,找出它不起作用的地方。您将函数命名为
sum
,然后在其中调用函数
sum
,以执行求和。更改函数的名称。另外,不要这样做
meanProof:
sum I更新了函数:如果你问为什么这个代码不起作用,应该包含一个最小的可复制示例。我还建议将函数分成几个小部分,找出它不起作用的地方。您将函数命名为
sum
,然后在其中调用函数
sum
,以执行求和。更改函数的名称。另外,不要这样做
meanProof:
sum I更新函数: