-1

I am new to R and I have a data table (df) like below:

id   month   year   count
___  _____   ____   ______
1     1      2017     12
1     2      2017     10
1     3      2017     13
2     1      2017     9
2     2      2017     18
2     3      2017     13
3     1      2017     12
3     2      2017     10
3     3      2017     10

From this I want to reshape the data frame from long to wide in the format which is shown below something like

id      1      2      3 
___     __    ___    ___
1       12     10     13
2       9      18     13
3       12     10     10

I tried melt(df).But throw an error.Any help is apprecited.

Ricky
  • 2,662
  • 5
  • 25
  • 57

1 Answers1

2

You can use spread from the tidyr package which is part of the tidyverse.

library(tidyverse)
df <- read_table("id   month   year   count
1     1      2017     12
1     2      2017     10
1     3      2017     13
2     1      2017     9
2     2      2017     18
2     3      2017     13
3     1      2017     12
3     2      2017     10
3     3      2017     10")

df %>% spread(month, count)
#> # A tibble: 3 x 5
#>      id  year   `1`   `2`   `3`
#> * <int> <int> <int> <int> <int>
#> 1     1  2017    12    10    13
#> 2     2  2017     9    18    13
#> 3     3  2017    12    10    10
markdly
  • 4,394
  • 2
  • 19
  • 27