|
| 1 | +alevels <- structure(function # Alternative levels |
| 2 | +### Create a pattern and a conversion function based on alternative |
| 3 | +### string literals. |
| 4 | +(... |
| 5 | +### Optional names are string literals to match; values are |
| 6 | +### corresponding factor levels. |
| 7 | +){ |
| 8 | + old2new <- c(...) |
| 9 | + if(is.null(names(old2new))){ |
| 10 | + names(old2new) <- old2new |
| 11 | + } |
| 12 | + to.rep <- names(old2new)=="" |
| 13 | + names(old2new)[to.rep] <- old2new[to.rep] |
| 14 | + list( |
| 15 | + paste(names(old2new), collapse="|"), |
| 16 | + function(x)factor(old2new[x], old2new)) |
| 17 | +### List of pattern and conversion function that returns factor. |
| 18 | +}, ex=function(){ |
| 19 | + |
| 20 | + ## Example 0: melt iris data with literal alternatives -> chr columns. |
| 21 | + ichr <- nc::capture_melt_single( |
| 22 | + iris[1,], |
| 23 | + part="Sepal|Petal", |
| 24 | + "[.]", |
| 25 | + dim="Length|Width") |
| 26 | + factor(ichr$part)#default factor levels are alphabetical. |
| 27 | + |
| 28 | + ## Example 1: melt iris data with alevels() -> factor columns. |
| 29 | + (ifac <- nc::capture_melt_single( |
| 30 | + iris[1,], |
| 31 | + part=nc::alevels("Sepal","Petal"), |
| 32 | + "[.]", |
| 33 | + dim=nc::alevels("Length","Width"))) |
| 34 | + ifac$part #factor with levels in same order as given in alevels(). |
| 35 | + |
| 36 | + ## Example 2: alevels(literals_to_match="levels_to_use_in_output"). |
| 37 | + tv_wide <- data.frame( |
| 38 | + id=0, |
| 39 | + train.classif.logloss = 1, train.classif.ce = 2, |
| 40 | + valid.classif.logloss = 3, valid.classif.ce = 4) |
| 41 | + nc::capture_melt_single( |
| 42 | + tv_wide, |
| 43 | + set=nc::alevels(valid="validation", train="subtrain"), |
| 44 | + "[.]classif[.]", |
| 45 | + measure=nc::alevels(ce="error_prop", auc="AUC", "logloss")) |
| 46 | + |
| 47 | + ## Example 3: additional groups which output character columns. |
| 48 | + nc::capture_melt_single( |
| 49 | + tv_wide, |
| 50 | + set_chr=list(set_fac=nc::alevels(valid="validation", train="subtrain")), |
| 51 | + "[.]classif[.]", |
| 52 | + measure_chr=list(measure_fac=nc::alevels(ce="error_prop", auc="AUC", "logloss"))) |
| 53 | + |
| 54 | +}) |
| 55 | + |
0 commit comments