library(tidyverse)
Using the sample code below, I want to use "mutate" or "mutate_at" to recode multiple columns into new columns based on the value of another column. Basically, I would like to recode the variables ending is "s" (q25s,q26s,etc...), based on the value of the corresponding non "s" variable. So for example, if q25 = 1, then q25s will be recoded so that 1 = 0, 2=0, 3=0, 4=1, 5=1, and 88=Missing, and the new name will be q25_new. If q25 does not equal 1, then is should not be recoded and q25_new should just be NA.
However, in order to achieve this I'm attempting to use tidyverse to create named vectors of column names, and then use "mutate", "recode", and "if_else" together with purr::map2.
I'm thinking something like the code below should be possible? I can't quite get it to work...and I feel like I need to use "paste0" somewhere to name all the new column variable names that start with "_new".
cols1<-Df %>%select(q25:q29)
cols2<-Df %>% select(q25s:q29s)
Df<- Df %>% map2(Df[cols1],Df[cols2],
~if_else(.x==1, mutate_at(vars (.y),funs(recode(.,`1`=0,`2`=0,`3`=0,`4`=1,`5`=1),"NA"))))
Here is the sample code.
Here is the sample code:
q25<-c(2,1,88,2,1)
q26<-c(2,88,88,88,2)
q27<-c(2,2,1,1,1)
q28<-c(88,1,1,2,2)
q29<-c(1,1,1,2,2)
q25s<-c(3,5,88,4,1)
q26s<-c(4,4,5,5,1)
q27s<-c(3,3,4,1,4)
q28s<-c(4,5,88,1,3)
q29s<-c(88,88,3,4,4)
Df<-data.frame(q25,q26,q27,q28,q29,q25s,q26s,q27s,q28s,q29s)
q..s
ifq..
is not equal to1
? – Psidom