Search code examples
rdataframetranspose

How can I transpose my data so it only have one row per group in R?


I have a dataframe in R with a variable (permno) which is a unique company ID. For each company I have estimated an Intercept, r2_12, sue and car3. As you can see below.

    Permno   Term      Estimate
1   10001 Intercept    0.020
2   10001     r2_12   -0.010
3   10001       sue    0.007
4   10001      car3    0.140
5   10025 Intercept    0.007
6   10025     r2_12   -0.004
7   10025       sue    0.001
8   10025      car3    0.020
9   10026 Intercept    0.020
10  10026     r2_12   -0.010
11  10026       sue    0.002
12  10026      car3    0.030

Now I want to transform the rows into columns, so I only have one row for each Permno. Meaning that the Intercept, r2_12, sue and car3 become 4 new columns like below:

 Permno Intercept  r2_12   sue car3
1  10001     0.020 -0.010 0.007 0.14
2  10025     0.007 -0.004 0.001 0.02
3  10026     0.020 -0.010 0.002 0.03

Does anyone know how I can do this in R?


Solution

  • You can do this with pivot_wider from the tidyr library:

    library(tidyr)
    
    df %>% 
      tidyr::pivot_wider(id_cols = Permno,
                         names_from = Term,
                         values_from = Estimate)
    
     Permno Intercept r2_12   sue  car3
       <dbl>     <dbl> <dbl> <dbl> <dbl>
    1   1001      0.02 -0.01 0.007  0.14
    
    

    Data

    df <- data.frame("Permno" = rep(1001, 4),
                     "Term" = c("Intercept", "r2_12", "sue", "car3"),
                     "Estimate" = c(0.020, -0.010, 0.007, 0.140))