Question

I have a data frame with GDP values for 12 South American countries over ~40 years. A snippet of the frame is as follows:

168     Chile  1244.1799 1972
169     Chile  4076.3207 1994
170     Chile  3474.7172 1992
171     Chile  2928.1562 1991
172     Chile  6143.7276 2004
173  Colombia   882.5687 1976
174  Colombia  1094.8795 1977
175  Colombia  5403.4557 2008
176  Colombia  2376.8022 2002
177  Colombia  2047.9784 1993

1) I want to order the data frame by country. The first ~40 values should pertain to Argentina, then next ~40 to Bolivia, etc.

2) Within each country grouping, I want to order by year. The first 3 rows should pertain to Argentina 2012, Argentina 2011, Argentina 2010, etc.

I can grab the data for each country individually using subset(), and then order it with order(). Surely I don't have to do this for every country and then use rbind()? How do I do it in one foul swoop?

3) Once I have the final product, I'd like to create 12 small, individual line graphs stacked vertically, each pertaining to a different country, which shows the trend of that country's GDP over the ~40 years. How I do create such a plot?

I'm sure I could find info on the 3rd question myself, but, well, I don't even know what such a graph is called in the first place..

Was it helpful?

Solution

Here is a solution with ggplot2. Assuming your data is in df:

library(ggplot2)
df$year.as.date <- as.Date(paste0(df$year, "-01-01")) # convert year to date
ggplot(df, aes(x=year.as.date, y=gdp)) + 
  geom_line() + facet_grid(country ~ .)

enter image description here

You don't actually need to sort by year and country, ggplot will handle that for you. Here is the data (clearly, only using 5 countries and 12 years, but this will work for your data). Also, I show you how to sort by two columns on the third line:

countries <- c("ARG", "BRA", "CHI", "PER", "URU")
df <- data.frame(country=rep(countries, 12), year=rep(2001:2012, each=5), gdp=runif(60))
df <- df[order(df$country, df$year),]   # <- we sort here
df$gdp <- df$gdp + 1:12 / 2
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top