apply command
I guess that the matrix dimension changed because matrix in R are filled by columns. Since you try: apply(b, 1, function(y) sort(y, na.last=F)) The second parameter make it scan matrix b row by row but store result by columns, which make the result be a matrix transposed. If you try: apply(b, 2, function(y) sort(y, na.last=F)) The second parameter means scan column by column, and the result matrix will have the same dimension with origin.
On Tue, Jan 19, 2010 at 6:31 PM, Tal Galili <tal.galili at gmail.com> wrote:
Hello Marco What I would do, is use "t" to transpose the matrix. Why it is that apply switches the matrix, is beyond my knowledge - and I would love to read more informed replies. Tal ----------------Contact Details:------------------------------------------------------- Contact me: Tal.Galili at gmail.com | ?972-52-7275845 Read me: www.talgalili.com (Hebrew) | www.biostatistics.co.il (Hebrew) | www.r-statistics.com/ (English) ---------------------------------------------------------------------------------------------- On Tue, Jan 19, 2010 at 12:27 PM, marco salvini <marco.salvini at gmail.com>wrote:
Can you please help on the issue? I using the apply command on a matrix below the example: Create a vector x =c(5, 3, 2:4, NA, 7, 3, 9, 2, 1, 5) create a matrix of 2 rows by 6 columns ?b=matrix(x, 2,6) ?print(b) ? ? [,1] [,2] [,3] [,4] [,5] [,6] [1,] ? ?5 ? ?2 ? ?4 ? ?7 ? ?9 ? ?1 [2,] ? ?3 ? ?3 ? NA ? ?3 ? ?2 ? ?5 using the command apply ?print(apply(b, 1, function(y) sort(y, na.last=F))) the output is a matrix of 6 rows by 2 columns. ? ? ?[,1] [,2] [1,] ? ?1 ? NA [2,] ? ?2 ? ?2 [3,] ? ?4 ? ?3 [4,] ? ?5 ? ?3 [5,] ? ?7 ? ?3 [6,] ? ?9 ? ?5 As you can see in the example I start with a matrix of (2 by 6) and the output of apply is a mtraxi of (6 by 2). This is very strange because I was expecting as output a matrix of the same dim (2 by 6) of the input matrix. I can solve this issues using an if statment on the dim of the matrix but if I am using a square matrix I am not able to control if the result of the apply is correct. Do anyone find a solution to this issue? thanks Marco ? ? ? ?[[alternative HTML version deleted]]
______________________________________________ R-help at r-project.org mailing list 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.
? ? ? ?[[alternative HTML version deleted]]
______________________________________________ R-help at r-project.org mailing list 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.