1

我跑了这个:

GroupSummary <- function(x){
    for (i in x) {
        if(i>0){
            p <-c(summary(x))
            r <- c(p)
        } else {if(i<0){
                n <-c(summary(x))
                r <- c(n)
            } else {stop}
        }
        return(r)
    }
}

x <- c(-1,-2,-3,-4,-5,-6,-7,-8,-9,-10,1,2,3,4,5,6,7,8,9,10)
GroupSummary(x)

结果我得到了这个:

   Min. 1st Qu.  Median    Mean 3rd Qu.    Max. 
 -10.00   -5.25    0.00    0.00    5.25   10.00 

我试图将它分成两组,一组用于正数,另一组用于负数,而不是将两者结合起来。我写的编码哪里出错了?欢迎任何提示或帮助谢谢

4

3 回答 3

1

使用内置的fivenum,您可以获得:

tapply(x,x>0,fivenum)
于 2013-06-27T13:43:19.167 回答
1

可以提倡aggregate吗?

> x <- c(-(1:10),1:10)

> aggregate(x, by=list(positive=x>0), summary)
  positive x.Min. x.1st Qu. x.Median x.Mean x.3rd Qu. x.Max.
1    FALSE -10.00     -7.75    -5.50  -5.50     -3.25  -1.00
2     TRUE   1.00      3.25     5.50   5.50      7.75  10.00

> aggregate(x, by=list(positive=x>0), fivenum)
  positive   x.1   x.2   x.3   x.4   x.5
1    FALSE -10.0  -8.0  -5.5  -3.0  -1.0
2     TRUE   1.0   3.0   5.5   8.0  10.0
于 2013-06-27T14:19:00.843 回答
0

这可能是所需的功能。默认情况下它适用于负/正,但您可以使用任何索引(默认 ind=NULL 创建正/负索引)。向量xind必须具有相同的长度,因此如果此条件不成立,我们将停止执行(使用stop)。

    groupSummary = function(x, ind=NULL) {
      if(is.null(ind)) {
        ind = character(length(x))
        ind[x>=0] = "positive"
        ind[x<0] = "negative"    
      }
      if(length(x)!=length(ind)) stop("'x' and 'ind' must have the same length.")
      out = do.call(rbind, tapply(x,INDEX=ind,FUN=summary))
      return(out)
    }

groupSummary(x)

         Min. 1st Qu. Median Mean 3rd Qu. Max.
negative  -10   -7.75   -5.5 -5.5   -3.25   -1
positive    1    3.25    5.5  5.5    7.75   10


set.seed(123) # to get the same output for 'colors' index
colors = sample(c("red", "blue", "green"), length(x), replace=TRUE)
groupSummary(x, colors)

      Min. 1st Qu. Median    Mean 3rd Qu. Max.
blue    -9   -5.00     -1 -3.0000     0.0    1
green  -10   -6.50     -4 -0.9091     5.0   10
red     -3   -0.75      4  3.1670     6.5    9

groupSummary(x, ind=1:3)
Error in groupSummary(x, ind = 1:3) : 
  'x' and 'ind' must have the same length.
于 2013-06-27T14:54:47.257 回答