简体   繁体   中英

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 oO?

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!

How about this using dplyr package?

df1<-data.frame("AB1"=c(1,2,3,4),"AB2"=c(1,2,3,4),"AB3"=c(1,2,3,4),"AB4"=c(1,2,3,4),"AB5"=c(1,2,3,4),"AB6"=c(1,2,3,4),"AB7"=c(1,2,3,4),"AB8"=c(1,2,3,4),"AB9"=c(1,2,3,4),"AB10"=c(1,2,3,4))

df1<-dplyr::mutate_at (df1,vars(AB1:AB4),list(~recode(.,'1'='1','2'='-1','3'='0','4'='0')))

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM