How to transform each digit of a number into an element of a vector in R?

Asked

Viewed 152 times

2

For example:

numero <- 516481

how can I transform each digit of that number into an element of an array, in order to access them by index? For if numero is a vector with each element being a digit I would have:

> print(numero)
[1] 5 1 5 4 8 1

And if you wanted to access the number 8, for example, simply request you for your position:

> numero[5]
[1] 8

As I’m dealing with 80-digit numbers, do by hand with the concatenate function c(5,1,6,4,8,1) is unviable. Know that my biggest goal is to be able to access the numbers by index, even if it is not through a vector.

1 answer

4


Can convert to character and use strsplit, converting then back to number:

numero <- 516481*10^9

algarismos <- as.integer(strsplit(as.character(format(numero, scientific = FALSE)), "")[[1]])

> algarismos
[1] 5 1 6 4 8 1 0 0 0 0 0 0 0 0 0

strsplit returns a list; the [[1]] indicates to take the first (and single, in case) element and return it as vector.

format(numero, scientific = FALSE) avoids error by using scientific notation when converting to character.

  • Carlos, your method works very well with few digit numbers, but it gets chaotic with large numbers. Assigning numero <- 1111111111111111111111111111111111 followed by algarismos <- as.integer(strsplit(as.character(numero), "")[[1]]) you can already see that something went wrong by the message Warning message:&#xA;NAs introduzidos por coerção console. And, when prompted to view the content of digits, with > algarismos console returns me [1] 1 NA 1 1 1 1 1 1 1 1 1 1 1 1 1 1 NA NA 3 3 Note that not only Nas have been entered as digits 3 that never existed

  • What’s more, the output does not contain the amount of items you should. numero had about 30 digits and the vector algarismos You don’t even have 20 items Any idea why that happened?

  • Updating: Withdrawing the request as.integer for conversion into whole, we have: algarismos <- strsplit(as.character(numero), "")[[1]] and algarismos gets the content: [1] "1" "." "1" "1" "1" "1" "1" "1" "1" "1" "1" "1" "1" "1" "1" "1" "e" "+" "3" "3" now it is clear where the Nas came from, apparently the R saves very large numbers in the form of power, which turns out to be a problem in this situation.

  • 1

    See help for as.character, just use format. I updated the response to include this option.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.