Skip to content

grouped colSums without for loops?

6 messages · Hans Ekbrand, jim holtman, Albert Greinoecker +1 more

#
Consider the following data.frame, d.

d <- data.frame(c("a","b","c","d","b","a"), c(1,4,85,3,4,1), c(7,6,2,4,15,33))
names(d) <- c("foo", "bar", "baz")
 
To get the colsum of d[[2]] for the rows that have d$foo == "a" I know
I can use

colSums(subset(d, d[[1]] == "a", select = 2))

But what is needed to get a list of colSums for d[[2]] for each factor
of d$foo ? Can it be done without a for loop?
#
Is this what you want?
$a
bar baz
  2  40

$b
bar baz
  8  21

$c
bar baz
 85   2

$d
bar baz
  3   4

        
On Tue, Mar 18, 2008 at 5:41 AM, Hans Ekbrand <hans at sociologi.cjb.net> wrote:

  
    
#
try:
aggregate(d[,2:3], by=list(d$foo), FUN=sum)

cheers,
Albert

Am Dienstag, den 18.03.2008, 11:41 +0100 schrieb Hans Ekbrand:
#
On Tue, Mar 18, 2008 at 05:57:59AM -0500, jim holtman wrote:
Yes! Thank you! the *apply functions seem very powerful, thanks again
for giving me a hint on how to use them.
#
See ?rowsum.  The other two suggestions are both shown in the Example
section as well (with comment).

Andy 

From: Hans Ekbrand
------------------------------------------------------------------------------
Notice:  This e-mail message, together with any attachme...{{dropped:15}}
#
On Tue, Mar 18, 2008 at 12:05:23PM +0100, Albert Greinoecker wrote:
Great! Now I can get a data.frame as well as a list, thanks!