Search code examples
rreshape2dcast

Reshaping the dataframe using dcast()


I am trying to reshape my dataframe using dcast() but I am getting this error

object 'newid' not found

I am not clear about the error. This is the original dataframe

 Grade    Week     Subject    Location    Marks
   6      January   English     IND        76.50
   6      January   English     US         52.50
   7      January   English     IND        24.00
   7      January   English     US         5.00
   8      February  English     IND        63.00
   8      February  English     US         40.25
   9      February  English     IND        63.00
   9      February  English     US         32.50
   10     March     English     IND        27.00
   10     March     English     US         4.50
   11     March     English     IND        10.00



tmp <- plyr::ddply(monthTotalDataFinal, .(Subject, Grade), 
          transform,newid = paste(Subject))
d2 <- dcast(tmp, formula = Subject+newid ~ Grade+Location+Week, 
              value.var  = 'Marks')

The required data frame is as follows:

Subject 6_IND 7_IND 6_US 7_US 8_IND 9_IND 8_US 9_US 10_IND 11_IND 10_US

English  77    24    53   5    63    63    40   33   27     10     5

Please give a suitable solution for this.


Solution

  • Using dplyr and tidyr, we can unite Grade, Location column and use spread to get data in wide format.

    library(dplyr)
    library(tidyr)
    
    df %>%
      unite(key, Grade, Location) %>%
      select(-Week) %>%
      spread(key, Marks)
    
    #  Subject 10_IND 10_US 11_IND 6_IND 6_US 7_IND 7_US 8_IND  8_US 9_IND 9_US
    #1 English     27   4.5     10  76.5 52.5    24    5    63 40.25    63 32.5
    

    Based on the comments we might need to create an identifier column for multiple Subject

    df %>%
      unite(key, Grade, Location) %>%
      select(-Week) %>%
      group_by(key, Subject) %>%
      mutate(row = row_number()) %>%
      spread(key, Marks)