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...
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))
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With