string - Working with the rep() function -
i'm using rep()
function repeat each element in string number of times. each character have contains information state, , need first 3 elements of character vector repeated 3 times, , fourth element repeated 5 times.
so lets have following character vectors.
al <- c("alabamacity", "alabamacityst", "alabamacitystate", "alabamazipcode") ak <- c("alaskacity", "alaskacityst", "alaskacitystate", "alaskazipcode") az <- c("arizonacity", "arizonacityst", "arizonacitystate", "arizonazipcode") ar <- c("arkansascity", "arkansascityst", "arkansascitystate", "arkansaszipcode")
i want end having following output.
alabamacity alabamacity alabamacity alabamacityst alabamacityst alabamacityst alabamacitystate alabamacitystate alabamacitystate alabamazipcode alabamazipcode alabamazipcode alabamazipcode alabamazipcode alabamazipcode ...
i able desired output following command, it's little inconvenient when i'm running through fifty states. plus, might have column 237 cities in alabama, , i'll inevitably run problems matching names in first column values in second column.
dat = data.frame(name=c(rep(al[1:3],each=3), rep(al[4],each=6), rep(ak[1:3],each=3), rep(ak[4],each=6))) dat dat2 = data.frame(name=c(rep(al[1:3],each=3), rep(al[4],each=6), rep(ak[1:3],each=3), rep(ak[4],each=6)), city=c(rep("x",each=15), rep("y",each=15))) dat2
of course, in real life, 'x' , 'y' won't single values.
so question concerns if there more efficient way of performing task. , closely related question, when become important ditch procedural programming in favor of oop in r. (not programmer, second part may stupid question) more importantly, task should oop related solution.
according ?rep
, times=
can vector. so, how this:
dat <- data.frame(name=rep(al, times=c(3,3,3,6)))
it more convenient if "state" data in list.
statedata <- list(al,ak,az,ar) data <- lapply(statedata, function(x) data.frame(name=rep(x, times=c(3,3,3,6)))) data <- do.call(rbind, data)
Comments
Post a Comment