Stats on every n rows for each column

前端 未结 2 2008
轻奢々
轻奢々 2021-01-23 04:03

I would like to calculate the mean and standard deviation for every nth (in my case every 6) rows (or samples). The following function gives me the means for every 6 rows (96 ro

2条回答
  •  误落风尘
    2021-01-23 04:57

    I think a possible reason that you got Error, warning message is because you applied it directly on the data.frame. For example

    set.seed(48)
    d1 <- as.data.frame(matrix(sample(1:40, 80*96, replace=T), ncol=80))
    rowMeans(matrix(d1, ncol=6, byrow=T))
    #Error in rowMeans(matrix(d1, ncol = 6, byrow = T)) : 'x' must be numeric
    #In addition: Warning message:
    #In matrix(d1, ncol = 6, byrow = T) :
    #  data length [80] is not a sub-multiple or multiple of the number of rows [14]
    

    You could unlist the data.frame

     res <- rowMeans(matrix(unlist(d1), ncol=6, byrow=T))
     dim(res) <- c(96/6, 80)
    length(res)
    #[1] 1280
    

    Crosschecking the results from @Matthew Lundberg's method

    res1 <- sapply(d1, function(x) colMeans(matrix(x, nrow=6)))
    
    all.equal(res,res1, check.attributes=F)
    [1] TRUE
    

提交回复
热议问题