【问题标题】:Calculate min, maximum and mean in R计算 R 中的最小值、最大值和平均值
【发布时间】:2016-04-14 06:07:52
【问题描述】:

我有 130 行和两列的数据集。 我想使用 R 计算秒列的每 5 行的平均值、最小值和最大值。通过使用 colMeans 和以下命令 rep(colMeans(matrix(data$Pb, nrow=5), na.rm=TRUE), each=5) 我能够计算每 5 行的平均值。但是我无法计算最大值和最小值,因为没有相同的内置函数。我按照here 的建议尝试了 5 行而不是 2 行。但是我收到一个错误,dim(X) must have a positive length. 有人可以帮助我了解我应该如何修复和计算上述数量吗?我的最终目标是每 5 行绘制最小值、平均值、最大值。

提前致谢。

【问题讨论】:

    标签: r


    【解决方案1】:

    如果我们正在寻找函数来查找matrix的每一列的maxmin,可以使用matrixStats中的colMaxscolMins

    library(matrixStats)
    colMaxs(mat)
    #[1]  7  8 20
    
    colMins(mat)
    #[1] 3 1 7
    

    但是,如果这是为每 5 行数据集列查找,请使用 gl 为每 5 行创建分组索引,然后在 by 的帮助下,我们得到 colMaxs 或 @987654332 @或colMeans

    by(data, list(gr=as.numeric(gl(nrow(data), 5, nrow(data)))), 
                     FUN = function(x) colMaxs(as.matrix(x)))
    

    同样的方法,我们可以找到colMinscolMeans

    by(data, list(gr=as.numeric(gl(nrow(data), 5, nrow(data)))),
                 FUN = function(x) colMins(as.matrix(x)))
    
    by(data, list(gr=as.numeric(gl(nrow(data), 5, nrow(data)))),
                 FUN = function(x) colMeans(as.matrix(x)))
    

    以上可以用dplyr以简洁的方式完成

     library(dplyr)
     data %>%
        group_by(gr = as.numeric(gl(nrow(.), 5, nrow(.)))) %>%
        summarise_each(funs(min, max, mean))
    

    要做plotting,我们可以用ggplot扩展它

    library(ggplot2)
    library(tidyr)
    data %>% 
        group_by(gr = as.numeric(gl(nrow(.), 5, nrow(.)))) %>%
        summarise_each(funs(min, max, mean)) %>%
        gather(Var, Val, -gr) %>% 
        separate(Var, into = c("Var1", "Var2")) %>%
        ggplot(., aes(x=factor(gr), y=Val, fill=Var2)) + 
               geom_bar(stat="identity")+
               facet_wrap(~Var1)
    

    数据

    mat <- matrix(c(3,1,20,5,4,12,6,2,9,7,8,7), byrow=T, ncol=3) 
    set.seed(24)
    data <- data.frame(Pb = sample(1:9, 42, replace=TRUE), Ps = rnorm(42))
    

    【讨论】:

    • 嗨@akrun,感谢您的帮助。绘图功能可以简化吗?我是 R 的新手,还没有使用过它。为每列创建了许多列,其中包含 mean 、 min 和 max 值。我如何绘制它,使其看起来像 Glen_b here 给出的答案。你能帮帮我吗?
    【解决方案2】:

    一个很好的函数是基本的by 函数与apply 的结合。下面是一个示例,您首先为函数创建组索引:

    m <- matrix(runif(130*2),130,2)
    group <- rep(seq(nrow(m)), each=5, length.out=nrow(m))
    res <- by(m, INDICES = group, FUN = function(x){apply(x, MARGIN=2, FUN=max)})
    class(res) # "by" class
    do.call(rbind, res) # matrix
    

    【讨论】:

    • 非常感谢您的帮助。
    猜你喜欢
    • 2016-11-04
    • 1970-01-01
    • 2014-11-20
    • 1970-01-01
    • 2020-03-01
    • 1970-01-01
    • 2016-09-15
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多