开发者

mapply recycling arguments

I have written a function that will transform a number in base 10 to another base (I'm only interested in base 2 - 9). My current functions to convert base 10 to base 2 looks like:

cb2 <- function(num){
    td<-{}
    a <- {}
    while (num 2 > 0 ){
        a <- num %% 2
        td <- paste(td,a, sep="")
        num <- as.integer(num / 2)              
    }   
    return(td)  
} 

And the usage would be:

sapply(1:10, cb2)

I would like to generalize this function and include the preferred base(s) as arguments to the function, ala开发者_如何学C...

convertbase <- function(num, base){
    td<-{}
    a <- {}
    while (num / base > 0 ){
        a <- num %% base
        td <- paste(td,a, sep="")
        num <- as.integer(num / base)               
    }   
    return(td)  
}

If I'm only interested in a single number converted into base 2-10, all is well:

mapply(convertbase, 10, 2:10)

However, if I want numbers 1:10 for base 2:10, I run into problems:

mapply(convertbase, 1:10, 2:10)
Warning message:
In mapply(convertbase, 1:10, 2:10) :
  longer argument not a multiple of length of shorter

Ideally, this function or set of functions would return a dataframe with separate columns for base 2-10, but I realize there's something missing between the code I have and the goal. Any help would be appreciated.


mapply applies the function to each row, whereas it seems to me that you want to apply the function to all combinations of number and base. This does the trick:

outer(1:10,2:9,Vectorize(convertbase))
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜