【问题标题】:How to calculate statistics over sequences of non zeros in a dataframe in R如何计算R中数据帧中非零序列的统计信息
【发布时间】:2018-04-04 15:29:03
【问题描述】:

我有一个包含如下序列的数据框:

r1=c(0,0,0,1.2,5,0.5,3.3,0,0,2.1,0.7,1,3.3,0,0,0,0,2.5,4.2,1,5.2,0,0,0,0)
r2=c(0,0,3.5,5.1,2.5,0,0,0,0.6,1.7,1.6,1.2,1.6,0,0,0,0,1.5,1.8,1.5,0,0,0,0,0)
r=as.data.frame(cbind(r1,r2))

我的实际数据包含更多的列和行。对于每一列,我想获得每个非零值序列的最大值的最小值/最大值/平均值(基本统计)。这意味着,考虑一列,我提取其每个连续非 0 值序列的最大值,然后对它们执行统计。

【问题讨论】:

  • 请注册和/或合并您的帐户(您可以在我们help center我的帐户部分找到有关如何执行此操作的信息),然后您就可以编辑和评论您自己的问题。

标签: r


【解决方案1】:

在这里,我编写了一些函数来将您的向量分解为单独的运行,提取您想要的值(运行中的最大值),然后应用您要求的基本统计信息。可能有更优雅或更有效的方法。

r1=c(0,0,0,1.2,5,0.5,3.3,0,0, 2.1,0.7,1,3.3,0,0,0,0,2.5,4.2,1,5.2,0,0,0,0)
r2=c(0,0,3.5,5.1,2.5,0,0,0,0.6,1.7,1.6,1.2,1.6,0,0,0,0,1.5,1.8,1.5,0,0,0,0,0)
r=as.data.frame(cbind(r1,r2))

my.stats.fun <- function(col){
  # sub fuctions
  remove.successive.0s <- function(col){ 
    col  <- c(col, 0)
    i0   <- which(col==0)
    i00  <- i0[which(diff(i0)==1)]
    col2 <- col[-i00]
    if(col2[1]==0){ col2 <- col2[-1] }  # pops first 0
    return(col2)
  }
  run.indicator <- function(col){
    i0   <- which(col==0)
    lr   <- length(i0)
    runs <- rep(1:lr, times=c(i0-c(0,i0[-lr])))
    col  <- col[-i0]
    runs <- runs[-i0]
    return(list(values=col, index=runs))
  }
  basic.stats <- function(maxes){ 
    return(c(min=min(maxes), ave=mean(maxes), max=max(maxes)))
  }

  # apply functions
  col   <- remove.successive.0s(col)
  runs  <- run.indicator(col)
  maxes <- aggregate(runs$values, by=list(runs$index), max)[,2]
  stats <- basic.stats(maxes)
  return(stats)
}
sapply(r, my.stats.fun)
#      r1       r2
# min 3.3 1.700000
# ave 4.5 2.866667
# max 5.2 5.100000

【讨论】:

    猜你喜欢
    • 2017-12-24
    • 1970-01-01
    • 2014-04-09
    • 2021-04-10
    • 2018-06-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多