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:
- SelfReframeNeg = selfrefneg
- SelfImmerseNeg = selfimmneg
- SelfImmerseNeu = selfimmneut
- OtherReframeNeg = socrefneg
- OtherImmerseNeg = socimmneg
- OtherImmerseNeu = socimmneut
This is the desired output:
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