[R] Script for conditional sums of vectors

Benjamin Gillespie gybrg at leeds.ac.uk
Mon Feb 4 11:17:26 CET 2013


Thanks everyone - this seems to be the most efficient answer,

I'll do a bit of reading around too as suggested.

Thanks again,

Ben Gillespie
Research Postgraduate

School of Geography
University of Leeds
Leeds
LS2 9JT


________________________________________
From: D. Rizopoulos [d.rizopoulos at erasmusmc.nl]
Sent: 04 February 2013 09:35
To: Benjamin Gillespie
Cc: r-help at r-project.org
Subject: Re: [R] Script for conditional sums of vectors

try this:

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)
DF <- data.frame(a, b, c)

with(DF, tapply(c, list(a, b), sum))


I hope it helps.

Best,
Dimitris


On 2/4/2013 10:29 AM, Benjamin Gillespie wrote:
> 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.
>

--
Dimitris Rizopoulos
Assistant Professor
Department of Biostatistics
Erasmus University Medical Center

Address: PO Box 2040, 3000 CA Rotterdam, the Netherlands
Tel: +31/(0)10/7043478
Fax: +31/(0)10/7043014
Web: http://www.erasmusmc.nl/biostatistiek/



More information about the R-help mailing list