[R] R WRONG CALCULATIONS - Please Help
Sarah Goslee
sarah.goslee at gmail.com
Mon Sep 14 19:06:42 CEST 2015
On Mon, Sep 14, 2015 at 11:11 AM, JORGE COLACO <j_colaco at utad.pt> wrote:
> I would greatly appreciate if you could let me know why the R does not make
> the right computations in the case below.
> Waiting for your reply
> Jorge Colaço
R made the correct computations: it did exactly what you told it. It
isn't R's fault that what you told it isn't what you meant. You want
to subtract the column means from each column; what you actual told R
was to subtract Xmean from X element by element column-wise, recycling
Xmean as necessary.
Here's what you meant:
X<-matrix(c(-1,0,1,-1,1,0,
0,0,1,1,1,-1,
-1,0,-1,1,0,1,
1,1,-1,-1,0,0,
0,0,1,1,-1,1),nrow=5,ncol=6,byrow=T)
Xmean <- colMeans(X)
sweep(X, 2, Xmean, "-")
Thank you for providing a simple reproducible example and clear idea
of what you intended. It made answering your question very
straightforward.
>
> R version 3.2.2 (2015-08-14) -- "Fire Safety"
> Copyright (C) 2015 The R Foundation for Statistical Computing
> Platform: i386-w64-mingw32/i386 (32-bit)
>
> R is free software and comes with ABSOLUTELY NO WARRANTY.
> You are welcome to redistribute it under certain conditions.
> Type 'license()' or 'licence()' for distribution details.
>
> R is a collaborative project with many contributors.
> Type 'contributors()' for more information and
> 'citation()' on how to cite R or R packages in publications.
>
> Type 'demo()' for some demos, 'help()' for on-line help, or
> 'help.start()' for an HTML browser interface to help.
> Type 'q()' to quit R.
>> X<-matrix(c(-1,0,1,-1,1,0,
> + 0,0,1,1,1,-1,
> + -1,0,-1,1,0,1,
> + 1,1,-1,-1,0,0,
> + 0,0,1,1,-1,1),nrow=5,ncol=6,byrow=T)
>
>>
> mean<-c(mean(X[,1]),mean(X[,2]),mean(X[,3]),mean(X[,4]),mean(X[,5]),mean(X[,6]))
>> mean
> [1] -0.2 0.2 0.2 0.2 0.2 0.2
>> X-mean
> [,1] [,2] [,3] [,4] [,5] [,6]
> [1,] -0.8 -0.2 0.8 -1.2 0.8 -0.2
> [2,] -0.2 0.2 0.8 0.8 0.8 -1.2
> [3,] -1.2 -0.2 -0.8 0.8 -0.2 0.8
> [4,] 0.8 0.8 -1.2 -0.8 -0.2 -0.2
> [5,] -0.2 -0.2 0.8 0.8 -0.8 0.8
>>
>
> Right Result Should Be:
>
> ans =
> -0.80000 -0.20000 0.80000 -1.20000 0.80000 -0.20000
> 0.20000 -0.20000 0.80000 0.80000 0.80000 -1.20000
> -0.80000 -0.20000 -1.20000 0.80000 -0.20000 0.80000
> 1.20000 0.80000 -1.20000 -1.20000 -0.20000 -0.20000
> 0.20000 -0.20000 0.80000 0.80000 -1.20000 0.80000
>
> [[alternative HTML version deleted]]
>
> ______________________________________________
> R-help at r-project.org mailing list -- To UNSUBSCRIBE and more, see
> https://stat.ethz.ch/mailman/listinfo/r-help
> PLEASE do read the posting guide http://www.R-project.org/posting-guide.html
> and provide commented, minimal, self-contained, reproducible code.
--
Sarah Goslee
http://www.functionaldiversity.org
More information about the R-help
mailing list