开发者

sweeping out colMeans and rowMeans

To sweep out colMeans, rowMeans and mean from columns, rows and observations respectively I use the following code:

a <- matrix(data=seq(from=2, to=60, by=2), nrow=6, ncol=5, byrow=FALSE)
b <- matrix(data=rep(colMeans(a), nrow(a)), nrow=nrow(a), ncol=ncol(a), byrow=TRUE)
c <- matrix(data=rep(rowMeans(a), ncol(a)), nrow=nrow(a), ncol=ncol(a), byrow=FALSE)
d <- matrix(data=rep(mean(a), nrow(a)*ncol(a)), nrow=nrow(a), ncol=ncol(a), byrow=FALSE)
e <- a-b-c-d

colMeans can 开发者_StackOverflow社区be sweep out by using this command

a1 <- sweep(a, 2, colMeans(a), "-")

Is there any single command to sweep out colMeans, rowMeans and mean? Thanks in advance.


What do you think eshould look like in this example? Perhaps your line should be e <- a-b-c+d so that e has zero mean.

The following code produces the same result as your calculation using b, c, and d (with your arithmetic progression example, a matrix of 0s). Change +to - if you insist.

 e <- t(t(a) - colMeans(a)) - rowMeans(a) + mean(a)   


Not that I know of, but why not just write your own? It's only four lines:

meanSweep <- function(x){
    tmp <- sweep(x,2,colMeans(x),"-")
    tmp <- sweep(tmp,1,rowMeans(x),"-")
    tmp <- tmp - mean(x)
    tmp
}

all.equal(e,meanSweep(a))
[1] TRUE
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜