jeudi 4 février 2021

Simultaneously transforming values in multiple columns

I have a set of variables in my df_1 that have to be "recoded" according to the same rule.

Variables/Columns: AB1 to AB10 Values: 1,2,3,4 New values 1 = 1 ; 2 = -1; 3 = 0; 4 = 0

the simple way tha i know of/use is the following:

df_1$AB1<- ifelse(df_1$AB1==1 , 1 ,  
                        ifelse(df_1$AB1== 2, as.integer(-1),
                               ifelse(df_1$AB1== 3, 0,
                                      ifelse(df_1$AB1== 4,0,NA))))

However i wonder whether it is possible to transform all 10 columns with one function using a more elegant way o.O?

Sidebar: no idea why but the ifelse function ingnores

ifelse(df_1$AB1== 2, -1,

thats why i had to use the quick fix

ifelse(df_1$AB1== 2, as.integer(-1),

Best regards and ty for your time lookig at this!

Aucun commentaire:

Enregistrer un commentaire