Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Mutating based on information from two columns in R

I have a dataframe that looks like this:

example <- data.frame(
  sub = c(101, 101, 101, 102, 102, 102),
  trialtype = c("ReframeNeg", "ImmerseNeu", "ImmerseNeg", "ImmerseNeu", "ImmerseNeg", "ReframeNeg"),
  condition = c("Self", "Self", "Self", "Other", "Other", "Other")
)

How can I create a new dataframe that combines the information from the trialtype and condition columns? For example, the first observation will be ‘SelfReframeNeg’ after combining trialtype and condition, which I will simplify to ‘selfrefneg’. The transformation mapping is as follows:

  1. SelfReframeNeg = selfrefneg
  2. SelfImmerseNeg = selfimmneg
  3. SelfImmerseNeu = selfimmneut
  4. OtherReframeNeg = socrefneg
  5. OtherImmerseNeg = socimmneg
  6. OtherImmerseNeu = socimmneut

This is the desired output:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

example_solution <- data.frame(
  sub = c(101, 101, 101, 102, 102, 102),
  trialtype = c("ReframeNeg", "ImmerseNeu", "ImmerseNeg", "ImmerseNeu", "ImmerseNeg", "ReframeNeg"),
  condition = c("Self", "Self", "Self", "Other", "Other", "Other"),
  trial = c("selfrefneg", "selfimmneut", "selfimmneg", "socimmneut", "socimmneg", "socrefneg")
)

Thank you!

>Solution :

If you have a limited number of possibile combinations you could use case_when

example %>%
  mutate(trial = paste0(condition, trialtype),
         trial = case_when(
           trial == "SelfReframeNeg" ~ "selfrefneg",
           trial == "SelfImmerseNeg" ~ "selfimmneg",
           trial == "SelfImmerseNeu" ~ "selfimmneut",
           trial == "OtherReframeNeg" ~ "socrefneg",
           trial == "OtherImmerseNeg" ~ "socimmneg",
           trial == "OtherImmerseNeu" ~ "socimmneut",
           TRUE ~ NA
         ))
#>   sub  trialtype condition       trial
#> 1 101 ReframeNeg      Self  selfrefneg
#> 2 101 ImmerseNeu      Self selfimmneut
#> 3 101 ImmerseNeg      Self  selfimmneg
#> 4 102 ImmerseNeu     Other  socimmneut
#> 5 102 ImmerseNeg     Other   socimmneg
#> 6 102 ReframeNeg     Other   socrefneg
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading