[R] Help Reformatting a Data table

Dennis Murphy djmuser at gmail.com
Wed Oct 19 10:08:20 CEST 2011


Here's one way to do it using the reshape package:

library('reshape')
cast(A, YEAR ~ TAX, value = 'NUMBER', fill = 0)
  YEAR A B
1 2000 2 3
2 2001 2 4
3 2002 3 3
4 2003 1 0
5 2004 0 2

HTH,
Dennis

On Tue, Oct 18, 2011 at 7:51 PM, Michael E. Steiper
<michaelsteiper at gmail.com> wrote:
> Hi, I am a relative newbie to R, so thanks in advance for the patience.
>
> I am interesting in changing a table with year data into a format that
> is friendlier for making bar charts. I currently have a table with the
> same year appearing a number of times as separate rows.  I want to
> change this so that each row is equivalent to a particular year.
>
> Here is an example of my current format:
>
> TAX     YEAR    NUMBER
> A       2000              2
> A       2001              2
> A       2002              3
> A       2003               1
> B       2000              3
> B       2001              4
> B       2002              3
> B       2004               2
>
> A<-data.frame(c("A", "A", "A", "A", "B","B","B","B"),
> c(2000,2001,2002,2003,2000,2001,2002,2004), c(2,2,3,1,3,4,3,2))
> colnames(A) = c("TAX", "YEAR", "NUMBER")
>
> I want to Change this to the following:
>
> YEAR    A       B
> 2000           2        3
> 2001            2       4
> 2002           3        3
> 2003           1        0
> 2004            0       2
>
> Any help would be appreciated!
>
> Of course, while I am posting, I'll also ask for any tips for creating
> a barchart with the X axis being "YEAR".
>
> Thanks for the time
>
> Mike
>
> ______________________________________________
> 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.
>



More information about the R-help mailing list