Swap Columns with Dichotomous Values

Hi all!

I'm not exactly sure how to articulate this--but here I go!

I have two columns that I am using for filter criteria. The columns contain either "Mother" or "Father". Some columns have just Mother and just Father, while others have a mix.

pool <- c("Mother","Father")

parents <- tibble(
  p1 = sample(pool,10,replace = T),
  p2 = sample(pool,10,replace = T),
  score = runif(10,1,7)
)

    p1     p2     score
   <chr>  <chr>  <dbl>
 1 Mother Mother  4.35
 2 Mother Father  5.03
 3 Father Father  2.80
 4 Father Mother  2.93
 5 Mother Father  4.21
 6 Father Mother  4.07
 7 Father Mother  4.60
 8 Father Father  1.59
 9 Mother Father  6.08
10 Father Father  4.76

What I would like to do:
Translate the data so that the column only contains one or the other, while still maintaining the structure. If filter based on "P1" I should be getting a "Mother Score", and if I filter based on "P2", I should get a "Father Score".

If something is unclear, I am happy to elaborate--thank you!!

I would do

library(tidyverse)
pool <- c("Mother","Father")

parents <- tibble(
  p1 = sample(pool,10,replace = T),
  p2 = sample(pool,10,replace = T),
  score = runif(10,1,7)
)

(parents_long <- pivot_longer(parents,
             cols = c(p1,p2),
             names_to = "p_ident",
             values_to = "score_ident"
            ))

This topic was automatically closed 21 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.