Home > front end >  In R, write a loop with regex column names
In R, write a loop with regex column names

Time:09-08

I need to write a loop with the following text iterating from columns dutycode221 until dutycode233.

Can you please help?

sched.na$dutycode221<-ifelse(sched.na$dutycode002<sched.na$dutycode221,sched.na$dutycode002,sched.na$dutycode221)

sched.na$dutycode222<-ifelse(sched.na$dutycode002<sched.na$dutycode222,sched.na$dutycode002,sched.na$dutycode222)

#...

sched.na$dutycode233<-ifelse(sched.na$dutycode002<sched.na$dutycode233,sched.na$dutycode002,sched.na$dutycode233)

CodePudding user response:

I don't think you need regex for this. This could be achieved by using the following functions from dplyr.

dplyr::mutate (creates or overwrites existing columns) dplyr::across (applies a function over several columns)

with an anonymous function <- function (x) { ifelse (x > dutycode002, dutycode002, x) }

  • Related