gpt4 book ai didi

r - mapply 回收参数

转载 作者:行者123 更新时间:2023-12-04 17:41:15 25 4
gpt4 key购买 nike

我编写了一个函数,可以将基数为 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)

我想概括这个函数,并包括首选的基数作为函数的参数,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)
}

如果我只对转换为基数 2-10 的单个数字感兴趣,那么一切都很好:
mapply(convertbase, 10, 2:10)

但是,如果我想要以 2:10 为基数的数字 1: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 的单独列,但我意识到我拥有的代码和目标之间缺少一些东西。任何帮助,将不胜感激。

最佳答案

mapply将该函数应用于每一行,而在我看来,您希望将该函数应用于数字和基数的所有组合。这是诀窍:

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

关于r - mapply 回收参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3323849/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com