mercredi 22 septembre 2021

How to mutate conditionally, while keeping original values intact in dplyr?

I'm working on my first dataset in R, so please forgive if this is a silly question but I have been struggling with it for days now.

My data looks something like this:

library(tidyverse)
tb1 <- tibble(ID = c(1,2,3,4,5),
       Quest_MF_1_1 = c(1,2,2,1,2),
       Quest_MF_1_2 = c(1,2,2,1,2),
       Quest_MF_2_1 = c(2,3,3,2,1),
       Quest_MF_2_2 = c(1,3,4,1,2),
       Quest_MV_1_1 = c(1,2,4,1,2),
       Quest_MV_1_2 = c(1,2,2,1,2),
       Quest_MV_2_1 = c(2,3,5,2,2),
       Quest_MV_2_2 = c(1,3,4,1,2))

tb_long <- tb1 %>%  pivot_longer(
  cols = 2:8,  
  names_to = c("Questionnaire", "Question", "Timepoint"),
names_pattern = "Quest_(.*)_(.*)_(.*)",
values_to = "score")

I would like to recode the values of all scores of MF_2 and MV_1 (5=1, 4=2, 3=3, 2=4, 1=5), while keeping the other values as they are. I have tried combining mutate and if_else but i haven't been able to figure out how to keep the scores of the other questions intact. Any ideas on how to do this?

In my actual data set i have two questionnaire with 20 and 30 questions each, measured at 20 different timepoints. For about halve of the questions of each questionnaire i need to recode te scores.

Aucun commentaire:

Enregistrer un commentaire