我已经写了一个函数,可以将基数为10的数字转换为另一个基数(我只对基数2-9感兴趣)。我当前将基数10转换为基数2的函数如下:
cb2 <- function(num){
td<-{}
a <- {}
while (num 2 > 0 ){
a <- num %% 2
td <- paste(td,a, sep="")
num <- as.integer(num / 2)
}
return(td)
}
它的用法是:
sapply(1:10, cb2)
我想推广这个函数,并将首选的基数作为函数的参数包括在内。
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)
}
如果我只对转换成基数2-10的单个数字感兴趣,那么一切都很好:
mapply(convertbase, 10, 2:10)
但是,如果我想用数字1:10作为基数2:10,我就会遇到问题:
mapply(convertbase, 1:10, 2:10)
Warning message:
In mapply(convertbase, 1:10, 2:10) :
longer argument not a multiple of length of shorter
理想情况下,这个函数或函数集将返回一个数据帧,其中包含基数为2-10的单独列,但我意识到我的代码和目标之间缺少一些东西。任何帮助都将不胜感激。
发布于 2010-07-24 05:14:53
mapply
将该函数应用于每一行,而在我看来,您似乎希望将该函数应用于数字和基数的所有组合。这样做是可行的:
outer(1:10,2:9,Vectorize(convertbase))
https://stackoverflow.com/questions/3323849
复制相似问题