Reputation: 569
I would like to do use some of Excel's pivot table functionalities in data frames of R. I can do what I want with some length coding, but I am wondering if there is an easy way to do it.
Assume I have the following data frame:
name<-c("Mexico","France","Chile","Germany","Sudan")
continent<-c("Am","Eur","Am","Eur","Afr")
population<-c(1000,2000,3500,2500,2000)
countries<-data.frame(name,continent,population)
I want to get a new data frame only with columns continents and population, where the population is summed over countries. So I want this get this one:
> continents
continent population
1 Am 4500
2 Eur 4500
3 Afr 2000
Any easy way for it?
Upvotes: 1
Views: 117
Reputation: 61214
you could use aggregate
> aggregate(population~continents, data=countries, FUN=sum)
continents population
1 Afr 2000
2 Am 4500
3 Eur 4500
Take a look at this answer for further alternatives
Upvotes: 4