I wrote a function that converts a number in base 10 to another base (I'm only interested in base 2 - 9). My current functions for converting base 10 to base 2 are as follows:
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 use will be:
sapply(1:10, cb2)
I would like to generalize this function and include the preferred base as arguments to the function, ala ...
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 one number converted to base 2-10, all is well:
mapply(convertbase, 10, 2:10)
However, if I want the numbers 1:10 for the base 2:10, I have 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 will return a data frame with separate columns for base 2-10, but I understand that there is a goal between the code that I have. Any help would be appreciated.
source
share