Quantcast
Channel: Active questions tagged r - Stack Overflow
Viewing all articles
Browse latest Browse all 201894

How to efficiently replace arguments in a function?

$
0
0

I'm working on a function that has an argument that can take any combination of value in 0:2

This argument is based on the "margin" system of prop.table function, but extends it so it can take several values: 0 is cell, 1 is row, 2 is column, but 1:2 is row and col and 0:2 is row, column, and cell.

I want to clarify this notation so that margin can take its value in c("all", "line", "column", "cell", 0, 1, 2), with last values needed for backward compatibility.

Here is my attempt using a switch (which I heard should be avoided):

ff = function(x, margin=c("all", "line", "column", "cell", 0, 1, 2)){
    if(!is.numeric(margin)){
        margin = switch(margin,
                        all = 0:2,
                        line = 1,
                        column = 2,
                        cell = 0)
        if(is.null(margin)) margin=0:2 #defaulting 
    }
    margin
}


ff(NULL, margin=1:2)
ff(NULL, margin="all")
ff(NULL, margin="cell")
ff(NULL, margin=c("column", "cell")) #error in switch (EXPR must be a length 1 vector)

If margin has an unexpected value, it would default it to 0:2. I'd rather use match.arg but I couldn't get it to accept a vector. Moreover, as it is now, the default vector will be coerced to character.

I also thought about replacing "all" by 0:2 etc. and then use unlist and unique but could not find any list replacement function that worked here.


Viewing all articles
Browse latest Browse all 201894

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>