Reshape based on repeating rows in first column in R

Viewed 90

I'd like to know how to reshape the following data set:

Here is the code to generate the following:

data.frame(Variable = c("Date","Location_1","Location_2","Date","Location_1","Location_2"),
           Monday = c("7/1/20","1","2","7/3/20","1","2"),
           Tuesday = c("7/2/20","5","2","7/4/20","5","2"))


Variable    Monday Tuesday 
Date        7/1/20  7/2/20     
Location_1     1       5                 
Location_2     2       2      
Date         7/3/20  7/4/20  
Location_1     1       5                
Location_2     2       2     

Into

Date      Location_1 Location_2
7/1/20        1          2          
7/2/20        5          2                  
7/3/20        1          2          
7/4/20        5          2          

I'm not sure why I'm struggling with using transpose properly, but it seems like an easy solution that I'm missing. Any help would be greatly appreciated.

Thanks!

3 Answers

Get the data in long format, create an identifier column and back to wide format.

library(dplyr)
library(tidyr)

df %>%
  pivot_longer(cols = -Variable) %>%
  select(-name) %>%
  group_by(Variable) %>%
  mutate(row = row_number()) %>%
  pivot_wider(names_from = Variable, values_from = value) %>%
  select(-row)

#  Date   Location_1 Location_2
#  <chr>  <chr>      <chr>     
#1 7/1/20 1          2         
#2 7/2/20 5          2         
#3 7/3/20 1          2         
#4 7/4/20 5          2         

In data.table using melt + dcast

library(data.table)

dcast(melt(setDT(df), id.vars = 'Variable'), rowid(Variable)~Variable,
      value.var = 'value')

Using base R you can do this:

df_t <- as.data.frame(t(df))[-1, ]
names(df_t) <- df$Variable

reshape(df_t,
        varying   = list(grep('Date',       names(df_t), value = T),
                         grep('Location_1', names(df_t), value = T),
                         grep('Location_2', names(df_t), value = T)),
        v.names   = c('Date', 'Location_1', 'Location_2'),
        direction = 'long')

This will add a time and id variable though, but that might be useful if you want to know which block of dates your new rows came from

We can also group_split and then reshape

library(dplyr)
library(purrr)
library(tidyr)
library(janitor)
df1 %>%
    group_split(grp = cumsum(Variable == 'Date'), keep = FALSE) %>%
    map_dfr(~ .x %>% 
            row_to_names(row_number = 1)) %>%
    pivot_longer(cols = -Date, values_drop_na = TRUE) %>% 
    pivot_wider(names_from  = Date, values_from = value)
Related