首页 文章

如何从r中的文件中读取直方图?

提问于
浏览
0

关于如何在R中计算直方图有很多资源 . 但是,我找不到任何解释如何从文件中读取就绪直方图的资源 . 例如,我有一个文本文件:

5 0.00413341649086988
15 0.00751482028214599
25 0.00896480849895891
...

其中第一列是中断,binning间隔的开始,第二列是在该bin处有事件的概率 . 如果我做:

d <- read.table("input.txt")

每当我使用 mean(d) 时,我都会收到错误,因为当然R并不想将其转换为直方图,只是为了方便计算平均值,标准偏差,ecc ....否则,我应该做 sum(d$V1*d$V2) 之类的事情 . 表示标准差, sqrt(sum((d$V1^2)*d$V2) - (sum(d$V1*d$V2))^2) ,等等 .

1 回答

  • 1

    如果您的文本文件如下所示:

    "breaks" "dens" "counts"
    "1" 0 0.75 3
    "2" 0.2 1.25 5
    "3" 0.4 1.5 6
    "4" 0.6 0.75 3
    "5" 0.8 0.75 3
    

    您可以通过将相关向量放入列表,然后分配其类属性来创建直方图对象 . 以下是执行此操作的函数的示例:

    make_hist <- function(df){
      his <- list()
      binwidth <- df$breaks[2]-df$breaks[1]
      # Assinging the breaks. Note that the last break is missing from the text file so we must add it
      his$breaks <- c(df$breaks, df$breaks[length(df$breaks)]+binwidth)
      his$counts <- df$counts
      his$density <- df$density
      his$mids <- df$breaks + binwidth/2
      his$xname <- deparse(substitute(df))
      his$equidist <- TRUE
      class(his) <- "histogram"
      return(his)
    }
    

    生成的对象的行为类似于使用 histogram() 创建的对象,例如在调用 plot(make_hist(his_txt))

相关问题