I want to perform some calculations in base 3 and need to have addition subtraction in that base. eg. 2+2 should become 11 in base 3
Asked
Active
Viewed 71 times
3 Answers
4
In the package sfcmisc
there is a function called digitsBase
that does such conversion.
library(sfcmisc)
digitsBase(2+2,base = 3)
# Class 'basedInt'(base = 3) [1:1]
# [,1]
# [1,] 1
# [2,] 1

Therkel
- 1,379
- 1
- 16
- 31
3
You may be able to use gmp
package
library(gmp)
as.character(x = as.bigz(2 + 2), b = 3)
#[1] "11"
Or write your own function. I modified the one from here
foo = function(dec_n, base){
BitsInLong = 64
Digits = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ";
if (base < 2 | base > nchar(Digits)){
stop(paste("The base must be >= 2 and <= ", nchar(Digits)))
}
if (dec_n == 0){
return(0)
}
index = BitsInLong
currentNumber = abs(dec_n)
charArray = character(0)
while (currentNumber != 0){
remainder = as.integer(currentNumber %% base)
charArray = c(charArray, substr(Digits, remainder + 1, remainder + 1))
currentNumber = currentNumber/base
}
charArray = inverse.rle(with(rle(rev(charArray)), list(values = if(values[1] == "0"){values[-1]}else{values},
lengths = if(values[1] == "0"){lengths[-1]}else{lenghts})))
result = paste(charArray, collapse = "")
if (dec_n < 0){
result = paste("-", result)
}
return(result)
}
USE
foo(dec_n = 2+2, base = 3)
#[1] "11"

d.b
- 32,245
- 6
- 36
- 77
0
If you want to convert a number from one base to other you can create the following function.Here you can convert a number from base 2 to 36 to base 2 to 36:
baseconverter <- function(number,baseGiven,baseRequire){
result = c()
if(baseRequire >36 || baseRequire<2 || baseGiven>36 || baseGiven<2){
return ("CustomError:Base is not proper")
}
Letters = LETTERS[seq( from = 1, to = 26 )]
numbers = 0:9
L = c(numbers,Letters)
rm(numbers)
rm(Letters)
number = substring(number,1:nchar(number),1:nchar(number))
convertToAlpha <- function(a) {
return(L[a+1])
}
alphaToDecimal <- function(a){
k = match(x = a , table = L )
return(k-1)
}
tempNum = 0
for (i in rev(number)){
digit = alphaToDecimal(i)
if(digit >= baseGiven || digit < 0){
return ("CustomError:Number is not proper")
}
tempNum = (tempNum*baseGiven) + digit
}
while(tempNum > baseRequire - 1){
result = c(convertToAlpha(tempNum - (baseRequire * floor(tempNum/baseRequire))),result)
tempNum = floor(tempNum/baseRequire)
}
result=c(tempNum,result)
return(paste(result,collapse = ""))
}
you can use the following function to convert the number in base m to base n:
baseconverter(number = 2+2 , baseGiven = 10 , baseRequire = 3)
hope it helps.

Mandar Sadye
- 689
- 2
- 9
- 30