Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Combine data in many row into a columnn

I have a data like this:

  year  Male
1 2011    8
2 2011    1
3 2011    4
4 2012    3
5 2012    12
6 2012    9
7 2013    4
8 2013    3
9 2013    3

and I need to group the data for the year 2011 in one column, 2012 in the next column and so on.

   2011  2012  2013
1   8     3     4 
2   1    12     3
3   4     9     3

How do I achieve this?

like image 358
nsaa Avatar asked Jan 19 '26 18:01

nsaa


2 Answers

One option is unstack if the number of rows per 'year' is the same

unstack(df1, Male ~ year)
like image 148
akrun Avatar answered Jan 22 '26 07:01

akrun


One option is to use functions from dplyr and tidyr.

library(dplyr)
library(tidyr)

dt2 <- dt %>%
  group_by(year) %>%
  mutate(ID = 1:n()) %>%
  spread(year, Male) %>%
  select(-ID)
like image 41
www Avatar answered Jan 22 '26 06:01

www



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!