-5

I have the following dataframe in R:

id    year    count 
1     2013    2
1     2014    20
2     2013    6
2     2014    7
2     2015    8
3     2011    13
...
999   2016    109

Each id is associated with at least 1 year, and each year has a count. The number of years associated with each id is pretty much random.

I wish to rearrange it into this format:

id    2011_count 2012_count 2013_count 2014_count ...
1     0          0          3          20         ...
2     0          0          6          7          ...
...
999   ...        ...        ...

I'm pretty sure someone else has asked a similar question, but I don't know how/what to search for.

Thanks!

Kontorus
  • 91
  • 1

1 Answers1

-1

Something like:

result <- reshape(aggregate(count~id+year, df, FUN=sum), idvar="id", timevar="year", direction="wide")
result[is.na(result)] <- 0
names(result) <- gsub("count\\.(.*)", "\\1_count", colnames(result))
apruden
  • 368
  • 2
  • 8