Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
254 views
in Technique[技术] by (71.8m points)

r - 如何有效地替换函数中的参数?(How to efficiently replace arguments in a function?)

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

(我正在处理一个函数,该函数的参数可以采用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.

(该参数基于prop.table函数的“ margin”系统,但对其进行了扩展,因此可以采用多个值:0是单元格,1是行,2是列,但是1:2是row和col和0:2是行,列和单元格。)

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.

(我想澄清一下这种表示法,以便可以在c("all", "line", "column", "cell", 0, 1, 2)中使用margin的值,并具有向后兼容所需的最后一个值。)

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

(这是我使用switch尝试(应该避免听到):)

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.

(如果margin具有意外值,它将默认为0:2。)

I'd rather use match.arg but I couldn't get it to accept a vector.

(我宁愿使用match.arg但我无法让它接受向量。)

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.

(我还考虑过将0:2等替换为“ all”,然后使用unlistunique但是找不到在此起作用的任何列表替换功能。)

  ask by Dan Chaltiel translate from so

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)
等待大神答复

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...