Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/r/66.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
在R中循环运行函数_R - Fatal编程技术网

在R中循环运行函数

在R中循环运行函数,r,R,我需要在循环中使用下面的函数,因为我有100个变量 binning <- function (df,vars,by=0.1,eout=TRUE,verbose=FALSE) { for (col in vars) { breaks <- numeric(0) if(eout) { x <- boxplot(df[,col][!df[[col]] %in% boxplot.stats(df[[col]])$out],plot=FALSE) non_

我需要在循环中使用下面的函数,因为我有100个变量

binning <- function (df,vars,by=0.1,eout=TRUE,verbose=FALSE) {
for (col in vars) {
  breaks <- numeric(0)
  if(eout) {
    x <- boxplot(df[,col][!df[[col]] %in% boxplot.stats(df[[col]])$out],plot=FALSE)    
    non_outliers <- df[,col][df[[col]] <= x$stats[5] & df[[col]] >= x$stats[1]]
    if (!(min(df[[col]])==min(non_outliers))) {
      breaks <- c(breaks, min(df[[col]]))
    }
  }
breaks <- c(breaks, quantile(if(eout) non_outliers else df[[col]], probs=seq(0,1, by=by)))  
  if(eout) {
    if (!(max(df[[col]])==max(non_outliers))) {
      breaks <- c(breaks, max(df[[col]]))
    }    
  }

  return (cut(df[[col]],breaks=breaks,include.lowest=TRUE))
}}

binning使用您的函数,您可以通过
lappy
,循环所有数值

# some data
dat0 <- data.frame(a=letters[1:10], x=rnorm(10), y=rnorm(10), z=rnorm(10))

# find all numeric by names
vars <- colnames(dat0)[which(sapply(dat0,is.numeric))]

# target data set
dat1 <- as.data.frame( lapply(vars, function(x) binning(dat0,x,eout=FALSE)) )
colnames(dat1) <- paste(vars, "_bin", sep="")
#一些数据
dat0
# some data
dat0 <- data.frame(a=letters[1:10], x=rnorm(10), y=rnorm(10), z=rnorm(10))

# find all numeric by names
vars <- colnames(dat0)[which(sapply(dat0,is.numeric))]

# target data set
dat1 <- as.data.frame( lapply(vars, function(x) binning(dat0,x,eout=FALSE)) )
colnames(dat1) <- paste(vars, "_bin", sep="")