DRY-ing a common R code pattern -


i've got imagine common pattern in r code. i've got data frame numeric vector, , want create factor variable based on particular values of numeric vector.

currently code looks like:

add_category <- function(sample) {    sample$category <- na    sample$category[sample$numeric_vars < 25000] <- '1. below 25k'    sample$category[sample$numeric_vars >= 25000] <- '2. above 25k'    sample$category[sample$numeric_vars >= 50000] <- '3. above 50k'    sample$category <- as.factor(sample$category)    return(sample) } 

the problem have code has bunch of repetition , can't test easily. i've been trying work out way make less repetitious, i've been banging head against few hours without success.

so question is, how replicate pattern in dry fashion in base r?

edit:

so make bit clearer, i'm aware can use cut fix particular problem. i'm more interested in strategies solve category of problem, recoding of separate variable based on test of particular instances of variable.

in hadley's advanced r's functional programming section uses example of recoding -99 na across number of columns. similar variety of values on 1 column.

i can shave couple of lines off. otherwise looks fine.

add_category <- function(sample) {     sample$category <- '1. below 25k'     sample$category[sample$numeric_vars >= 25000] <- '2. above 25k'     sample$category[sample$numeric_vars >= 50000] <- '3. above 50k'     return(sample) } 

it should factors.


Comments

Popular posts from this blog

javascript - Using jquery append to add option values into a select element not working -

Android soft keyboard reverts to default keyboard on orientation change -

Rendering JButton to get the JCheckBox behavior in a JTable by using images does not update my table -