Home > database >  Writing function with `while` failed
Writing function with `while` failed

Time:10-19

I am writing codes about changing decimal numbers to binary numbers.

This is my code with while and it worked.

i <- 1
binary_vec <- rep(0, 5)
x <- 15
while (i <= 5) {
  binary_vec[i] <- x %% 2
  x <- x %/% 2
  i <- i   1
}
binary_vec

However, I tried to write this code as a function and it failed.

i <- 1
decimal_to_binary <- function(x) {
  binary_vec <- rep(0, 5)
  while (i <= 5) {
    binary_vec[i] <- x %% 2
    x <- x %/% 2
    i <- i   1
  }
}
decimal_to_binary(22)
binary_vec

If I type decimal_to_binary(22), the result of binary_vec is supposed to be 01101 but it is not.

I want to know what's wrong.

CodePudding user response:

You are 99% of the way there! Move i inside the function and return the binary_vec object:

decimal_to_binary <- function(x) {
  i <- 1
  binary_vec <- rep(0, 5)
  while (i <= 5) {
    binary_vec[i] <- x %% 2
    x <- x %/% 2
    i <- i   1
  }
  binary_vec
}
decimal_to_binary(22)

Edits for a for loop version:

decimal_to_binary_for <- function(x, n=5) {
  binary_vec <- NULL
  for (i in 1:n) {
    binary_vec[i] <- x %% 2
    x <- x %/% 2
  }
  binary_vec
}
decimal_to_binary_for(22)
# [1] 0 1 1 0 1
decimal_to_binary_for(512, n=12)
# [1] 0 0 0 0 0 0 0 0 0 1 0 0
  • Related