[R] Fwd: Re: sum data from data.frame in a matrix

Nicolas Gutierrez nicolasg at uw.edu
Wed Feb 23 09:27:12 CET 2011


Hi Dennis,

Thanks for your quick response and sorry for not being clear. That 
helped, but I need an actual matrix of e.g., 12 x 12 and those functions 
give me a matrix with only the "filled" locations. I need a 12 by 12 
matrix with sums (0 if there's not data and the actual sum where there 
is) as follows:

   1 2 3 4 5 6 7 8 9 10 11 12
1 0 0 0 . . . . . .  0  0  0
2 0 0 0 .
3 0 0 0 .
.
.
10		    0 81  0
11                  0  0 30
12                 95  0  0

Any hints?

THANKS!!
Nico


-------- Original Message --------
Subject: 	Re: [R] sum data from data.frame in a matrix
Date: 	Wed, 23 Feb 2011 00:10:52 -0800
From: 	Dennis Murphy <djmuser at gmail.com>
To: 	Nicolas Gutierrez <nicolasg at uw.edu>



Hi:

...and a second way, using the reshape2 package:

library(reshape2)
dcast(df, yloc ~ xloc, value_var = 'yield', fun = sum)
    yloc 10 11 12
1   10  0 81  0
2   11  0  0 30
3   12 95  0  0


Dennis

On Tue, Feb 22, 2011 at 11:30 PM, Nicolas Gutierrez <nicolasg at uw.edu
<mailto:nicolasg at uw.edu>> wrote:

     Hi all (again),

     I have a data frame "pop":

        xloc  yloc  yield
     1  10    12    95
     2  11    10    81
     3  12    11    20
     4  12    11    10

     And I want to get the sum of yield for the cell (pop$xloc, pop$yloc)
     in a matrix as follows:

                 xloc
               10  11  12
            10 0   81  0
       yloc  11 0   0   30
            12 95  0   0


     Any ideas? thanks!

     Nico

     ______________________________________________
     R-help at r-project.org <mailto: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.



More information about the R-help mailing list