r - How to apply a function over two series of sequentially labelled variables without using column numbers? -
i need apply function using 2 sets of sequentially labelled variables , attach new set of variables data frame. need without referring column numbers in code.
more specifically, here simple task trying do:
dat <- data.frame(sec1 = sample(c(0:3),10,replace=t) , sec2 = sample(c(0:4),replace=t) , sec3 = sample(c(0:4),replace=t),pri1 = sample(c(0:3),10,replace=t) , pri2 = sample(c(0:4),replace=t) , pri3 = sample(c(0:4),replace=t) ) dat$rel1 <- ifelse(dat$pri1>0,dat$sec1/dat$pri1,na) dat
i want repeat "ifelse" function shown above without typing repeatedly each set of variables.
i must say, asked similar questions , received helpful answers (eg1 , eg2) in case responses either used column number in code, or example on single set of sequentially labelled variable. not manage revise suggested code solve particular problem.
any suggestion appreciated.
dat_n <- cbind(dat, mapply(function(x, y) ifelse(y>0,x/y,na) ,dat[grepl("sec",names(dat))], dat[grepl("pri",names(dat))])) > dat_n sec1 sec2 sec3 pri1 pri2 pri3 rel1 sec1 sec2 sec3 1 2 1 2 3 3 0 0.6666667 0.6666667 0.3333333 na 2 3 3 4 0 2 4 na na 1.5000000 1.00 3 1 0 3 1 4 4 1.0000000 1.0000000 0.0000000 0.75 4 2 4 1 3 3 2 0.6666667 0.6666667 1.3333333 0.50 5 2 0 2 3 4 1 0.6666667 0.6666667 0.0000000 2.00 6 1 1 2 1 3 0 1.0000000 1.0000000 0.3333333 na 7 1 3 4 0 2 4 na na 1.5000000 1.00 8 1 0 3 1 4 4 1.0000000 1.0000000 0.0000000 0.75 9 3 4 1 2 3 2 1.5000000 1.5000000 1.3333333 0.50 10 1 0 2 2 4 1 0.5000000 0.5000000 0.0000000 2.00
Comments
Post a Comment