Here we are explaining how to write an R program to convert a decimal number into binary by creating a recursion. Give the required number as an argument to the recursive function. Conversion into binary is done by dividing the number successively by 2 and the remainder is printed in reverse order.
Given below are the steps which are used in the R program to convert a decimal number into binary. In this R program, we give the number directly to the function convert_to_binary(). Check if the given decimal number is greater than 1 if yes divide the number successively by 2. The remainder is printed in reverse order.
convert_to_binary <-
function(decnum) {
if(decnum > 1) {
convert_to_binary(as.integer(decnum/2))
}
cat(decnum %% 2)
}
convert_to_binary(52)
## 110100
convert_to_binary(87)
## 1010111
convert_to_binary(204)
## 11001100
convert_to_binary(76)
## 1001100