Reshape data - Wide to Long

Hello!

I have a dataset in the form:

df <- data.frame(name = c("Tom", "Henry", "Linda"),
                gpa= c(3.5, 3, 3.7),
                friend1_name = c("David", "Anita", "Jay"),
                friend1_gpa = c(2.9, 3.8, 3.1),
                friend2_name = c("", "Selena", "William"),
                friend2_gpa = c(NA, 3.6, 3.5),
                friend3_name = c("", "Greg", "Olivia"),
                friend3_gpa = c(NA, 3.3, 3.4),
                friend4_name = c("", "Helen", NA),
                friend4_gpa = c(NA, 3.6, NA))

And I want it in the long-form with just variables name, gpa, friend_name and friend_gpa. Missing values can be dropped. I am struggling with the reshape function ..

Thank you so much!


library(tidyverse)
(names_df <- select(
  df,
  name, gpa,
  starts_with("friend") & ends_with("name")
))
(gpa_df <- select(
  df,
  name, gpa,
  starts_with("friend") & ends_with("gpa")
))

(names_long <- pivot_longer(names_df,
  cols = c(-name, -gpa), names_sep = "_",
  names_to = c("friend", "junk"),
  values_to = "friend_name"
))
(gpa_long <- pivot_longer(gpa_df,
  cols = c(-name, -gpa), names_sep = "_",
  names_to = c("friend", "junk"),
  values_to = "friend_gpa"
))

almost <- bind_cols(names_long,
                    gpa_long, 
                    .name_repair = "minimal")
almost %>% select(unique(names(almost)),
                  -junk, -friend)
1 Like

Thank you so very much!

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.

If you have a query related to it or one of the replies, start a new topic and refer back with a link.