rreshapelong-format-datawide-format-data

R reshaping the data


data <- data.frame(
  T2_husband = rnorm(5),
  T2_wife = rnorm(5),
  T1_husband = rnorm(5),
  T1_wife = rnorm(5),
  Dyad_ID = 1:5
)

I have 5 columns in the dataset. However, I want to make dataset to have following columns:


# Reshape the dataset
reshaped_data <- data %>%
  pivot_longer(
    cols = c(T1_husband, T1_wife, T2_husband, T2_wife), # Columns to reshape
    names_to = c("Time", "Role"),                      # Split column names into "Time" and "Role"
    names_sep = "_"                                    # Separator is "_"
  ) %>%
  pivot_wider(
    id_cols = c(Dyad_ID, Role), # Keep Dyad_ID and Role as unique identifiers
    names_from = Time,          # Reshape Time into separate columns
    values_from = value         # Values go into "T1" and "T2" columns
  )

# Add My_* and Partner_* columns
reshaped_data <- reshaped_data %>%
  group_by(Dyad_ID) %>% # Group by Dyad_ID to match partner roles
  mutate(
    My_T1 = T1,
    My_T2 = T2,
    Partner_T1 = T1[Role != first(Role)], # Select T1 where Role is not the current Role
    Partner_T2 = T2[Role != first(Role)]  # Select T2 where Role is not the current Role
  ) %>%
  ungroup() %>% # Remove grouping
  select(Dyad_ID, Role, My_T1, My_T2, Partner_T1, Partner_T2)

This is what I tried, but I think it did not work what I intended.


Solution

  • I think you just need to slightly modify how you create Partner_T1 and Partner_T2, the rest of the code is identical to yours

    # Reshape the dataset
    reshaped_data <- data %>%
      pivot_longer(
        cols = c(T1_husband, T1_wife, T2_husband, T2_wife), # Columns to reshape
        names_to = c("Time", "Role"),                      # Split column names into "Time" and "Role"
        names_sep = "_"                                    # Separator is "_"
      ) %>%
      pivot_wider(
        id_cols = c(Dyad_ID, Role), # Keep Dyad_ID and Role as unique identifiers
        names_from = Time,          # Reshape Time into separate columns
        values_from = value         # Values go into "T1" and "T2" columns
      )
    
    
    reshaped_data <- reshaped_data %>%
      group_by(Dyad_ID) %>% # Group by Dyad_ID to match partner roles
      mutate(
        My_T1 = T1,
        My_T2 = T2,
        Partner_T1 = ifelse( Role == "husband", T1[Role != first(Role)], T1[Role == first(Role)]), # Select T1 where Role is not the current Role
        Partner_T2 = ifelse( Role == "husband", T2[Role != first(Role)], T2[Role == first(Role)])  # Select T2 where Role is not the current Role
      ) %>%
      ungroup() %>% # Remove grouping
      select(Dyad_ID, Role, My_T1, My_T2, Partner_T1, Partner_T2)