Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
410 views
in Technique[技术] by (71.8m points)

r - How to produce time series for each row of a data frame with an unnamed first column

So this is I'm sure a fairly elementary problem. I have a data frame that has data for 10 years for a bunch of countries. It looks like this. The data frame is df.

                    X2003 X2004 X2005 X2006 X2007 X2008 X2009 X2010 X2011 X2012
Afghanistan         7.321 7.136 6.930 6.702 6.456 6.196 5.928 5.659 5.395 5.141
Albania             2.097 2.004 1.919 1.849 1.796 1.761 1.744 1.741 1.748 1.760
Algeria             2.412 2.448 2.507 2.580 2.656 2.725 2.781 2.817 2.829 2.820
Angola              6.743 6.704 6.657 6.598 6.523 6.434 6.331 6.218 6.099 5.979
Antigua and Barbuda 2.268 2.246 2.224 2.203 2.183 2.164 2.146 2.130 2.115 2.102
Argentina           2.340 2.310 2.286 2.268 2.254 2.241 2.228 2.215 2.201 2.188

The first column is metadata. It hasn't got a name. I'd like to use qplot to plot time series for each of the rows. Something like the following command:

library(ggplot2)
qplot (data = df, binwidth = 1, geom="freqpoly") but I get the following error

Error: stat_bin requires the following missing aesthetics: x. 

I would like to set x = first column but I don't have a name on that column. Do I have to create a first column of country names? If so, how do I do that? Seems like there should be an easier way. Sorry if this is so elementary.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

following your comments, I guess you want this kind of graphic?

# Create a "long" data frame rather than a "wide" data frame.

country <- rep(c("Afghanistan", "Albania", "Algeria","Angola",
             "Antigua and Barbuda", "Argentina"),each = 10, times = 1)
year <- rep(c(2003:2012), each = 1, times = 6)
value <- runif(60, 0, 50)

foo <- data.frame(country,year,value,stringsAsFactors=F)
foo$year <- as.factor(foo$year)

# Draw a ggplot figure

ggplot(foo, aes(x=year, y = value,group = country, color = country)) +
    geom_line() +
    geom_point()

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...