Changing positions on a numeric value

Hi, someone knows if there is a way to change positions of values on numeric value? For example, if I have the number 2.1456, can I change places for "2" and "6"?

What tells you which digits to swap? Is it position (swap the ones position with the ten-thousandths position), specific digits (swap the first instance of 2 with the first instance of 6) or what?

of course you can:

number_swap <- function(x, from, to) {
  str <- as.character(x)
  str <- unlist(strsplit(str, ""))
  str[c(from, to)] <- str[c(to, from)]
  paste0(str, collapse = "") |> as.numeric()
}

and then

number_swap(12345, 1, 2)

gives

[1] 21345
2 Likes

This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.

If you have a query related to it or one of the replies, start a new topic and refer back with a link.