I am trying to write a for loop that can reorganize a dataframe in to a table for publication, e.g. in excel.
Here is a small sample of the data data for my problem:
df <- data.frame(ST = c("NY", "NJ", "PA", "NY", "NJ", "PA"),
YR = c(2010, 2010, 2010, 2011, 2011, 2011),
X = c(.25, .24, .23, .24, .23, .22))
I would like to produce a table that lists each state once in a "State" column, each year as a row name titled "X Year" and each X value under the proper year. In this case, it would look like this, minus the "...":
State | 2010 Pop | 2011 Pop
NY ..... .25 .............. .24
NJ .......24................ .23
PA ..... .23 ............... .22
I have about a dozen years and data for all states, so I can do this laboriously by making a dataframe for each year, renaming the column names, binding the columns, and eliminating repeated ST columns. But, my intuition is that there is a more efficient way to do this. Would appreciate help thinking through this. Thanks!