Search code examples
rreshape

How to reshape a data frame with multiple values for each id? (like pivot table in excel)


I have this data frame:

data <- data.frame(id=sample(1:10,2000,replace = T),value=sample(100:10000,2000,replace = T))
> head(data)
  id value
1  4  2032
2  3  2512
3  9  8925
4  8  8527
5  6  5176
6  9  8182

Now I want value for each id as colnames and the values are to be rows that correspond to the id.

What I want is not to summarise but to group the values according to id and need to convert the id into columns.


Solution

  • This should work:

    library(tidyverse)
    
    data %>% 
      group_by(id = paste("id", id, sep = "_")) %>%
      mutate(rn = row_number()) %>%
      spread(id, value) %>%
      select(-rn)
    

    Output (first 10 rows):

        id_1 id_10  id_2  id_3  id_4  id_5  id_6  id_7  id_8  id_9
       <int> <int> <int> <int> <int> <int> <int> <int> <int> <int>
     1  8161   576  4921  5965  8969  8419  7898  5724  6513  7475
     2  8526  8121  5200  7847  4033  9348  5051  4430  9320  2973
     3  4587  4505  1747  6179  6358   234  5649  5780  3579  4986
     4  2609  9058  5709  4284  4068   523  9156  3253  6753  5570
     5  1261  4533  5954  7703  2460  2171  4196  7576  7118  8702
     6  3125  8303  2364  9305  9094  1211  3439  8201  5268  6794
     7  3464   657  2917  4831  6154  3125  9964  9324  1917  7439
     8  6601  2297  4163  7866  6701  6336   262  6725  7646  5361
     9  3042  4296  9312  8990   366  5891  3984  4675  7289  9549
    10  4829  5565  8841   775  5482  9519  1084  1845  4735  3467
    # ... with 203 more rows
    

    The tail of the dataset looks like:

       id_1 id_10  id_2  id_3  id_4  id_5  id_6  id_7  id_8  id_9
      <int> <int> <int> <int> <int> <int> <int> <int> <int> <int>
    1  2723    NA    NA    NA    NA    NA    NA    NA  7147    NA
    2  7746    NA    NA    NA    NA    NA    NA    NA  1809    NA
    3  4281    NA    NA    NA    NA    NA    NA    NA  8140    NA
    4    NA    NA    NA    NA    NA    NA    NA    NA  6564    NA
    5    NA    NA    NA    NA    NA    NA    NA    NA  6001    NA
    6    NA    NA    NA    NA    NA    NA    NA    NA  3471    NA