Skip to content
Back to formatted view

Raw Message

Message-ID: <510F8711.5080205@ymail.com>
Date: 2013-02-04T10:01:53Z
From: Pascal Oettli
Subject: Script for conditional sums of vectors
In-Reply-To: <894643FDEA3A854A89B3E828737E2B1FF3003D4CDA@HERMES8.ds.leeds.ac.uk>

Hello,

First, don't use "data" for a data frame, as it is a R function.

Here is a way to do what you are looking for:

a=c(1,1,1,1,1,1,2,2,2,2,2,2)
b=c(1,1,1,2,3,4,1,1,2,2,3,4)
c=c(400,200,300,100,500,300,200,100,500,400,200,100)

dat=data.frame(a=a,b=b,c=c)

dat.sum <- aggregate(c ~ a+b, dat, sum)
dat.sum <- reshape(dat.sum, timevar='b', idvar='a', direction='wide')

colnames(dat.sum) <- c('a','b.1','b.2','b.3','b.4')

HTH,
Pascal


Le 04/02/2013 18:29, Benjamin Gillespie a ?crit :
> Hi guys,
>
> I hope you can help me with this (probably) simple query:
>
> I have a data frame:
>
> --------------------------
>
> a=c(1,1,1,1,1,1,2,2,2,2,2,2)
> b=c(1,1,1,2,3,4,1,1,2,2,3,4)
> c=c(400,200,300,100,500,300,200,100,500,400,200,100)
>
>
> data=data.frame(a=a,b=b,c=c)
>
> --------------------------
>
> And I would like to get the following output:
>
> --------------------------
>
> 	b
> a	1	2	3	4
> 1	900	100	500	300
> 2	300	900	200	100
>
> --------------------------
>
> The values in the output represent the sum of values "c" in data frame "data", for each "a" and "b" combination.
>
> For example, where "a" = 1 and "b" = 1, the output is 400+200+300 = 900.
>
> Please would anyone be able to provide a script to create my desired output?
>
> Many thanks in advance,
> 		
> Ben Gillespie
> Research Postgraduate
>
> School of Geography
> University of Leeds
> Leeds
> LS2 9JT
>
>
> ______________________________________________
> 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.
>