Search code examples
rvariablesmerge

Is there an R function to merge two variables into a new one, so that a new cell is written only if a certain entry of another variable is given?


example data structure:

dats_long <- data.frame (dv  = c("Unt", "Dis", "Emp"),
                  rating = c(100, 53, 99),
                  unt = c(NA, NA, NA),
                  dis = c(NA, NA, NA),
                  emp = c(NA, NA, NA))

There are three measurements per participant (long format), where three DVs were extracted from a vignette survey and the scoring is stored in a separate variable ("rating").

Is there a way to create three new separate DV columns ("unt", "dis", "emp", in the example data structure still NAs) with only the corresponding ratings being written?

Target output:

dats_long <- data.frame (dv  = c("Unt", "Dis", "Emp"),
                  rating = c(100, 53, 99),
                  unt = c(100, NA, NA),
                  dis = c(NA, 53, NA),
                  emp = c(NA, NA, 99))

Tried the following (example for "dis"), did not write anything

dats_long %>% mutate(dis = case_when( dv == "Dis" ~ rating ))

And the

dats_long$dis[dats_long$dv == "Dis"] <- dats_long$rating 

did not work either as it simply pastes not every third, but every value of "score" for the newly created variable, so that a lag emerges.

Many thanks for your help!


Solution

  • mutate(dats_long,
          unt = if_else(dv == "Unt", rating, NA_integer_), 
          dis = if_else(dv == "Dis", rating, NA_integer_), 
          emp = if_else(dv == "Emp", rating, NA_integer_))
    
       dv rating unt dis emp
    1 Unt    100 100  NA  NA
    2 Dis     53  NA  53  NA
    3 Emp     99  NA  NA  99