views:

135

answers:

2

First I will have to apologise for my ignorance as I'm sure this is a very simple question but I am very new to R. My question is that I have a data frame that looks like this;

countrydes       Insured

USA               4500
CANADA            4500 
USA               7500
CANADA            7600

All I want to do is aggregate the sum of the insured value by country and produce a bar graph e.g.

countrydes        Insured 

USA                12000       
Canada             12100

Many thanks.

+2  A: 

You could simply sum each one separatly. Let's call your data frame df :

USA <- sum(df[df$countrydes=="USA",]$Insured)
CANADA <- sum(df[df$countrydes=="CANADA",]$Insured)

But with aggregate() you can handle all the countries in one line.

 aggsumcount <- aggregate(x=df$Insured,by=list(df$countrydes),FUN=sum)
Etiennebr
+3  A: 

This will do the trick:

# Define your data
dfr <- data.frame(
   countrydes=rep(c("USA", "CANADA"), 2), 
   Insured=c(4500, 4500, 7500, 7600))
# Sum by country
totals <- with(dfr, by(Insured, countrydes, sum))
# Plot the answer
barplot(totals)

(As Etiennebr mentioned, you could use aggregate instead of by, in which case you need to coerce countrydes to be a list.)

Richie Cotton