Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to extract a number into digits using R?

Suppose I have a number: 4321

and I want to extract it into digits: 4, 3, 2, 1

How do I do this?

like image 643
user2717901 Avatar asked Aug 26 '13 11:08

user2717901


People also ask

How do I separate numbers into digits in R?

To split a number into digits in R, we can use strsplit function by reading the number with as. character and then reading the output with as. numeric.

How do I extract digits from a string in R?

In this method to extract numbers from character string vector, the user has to call the gsub() function which is one of the inbuilt function of R language, and pass the pattern for the first occurrence of the number in the given strings and the vector of the string as the parameter of this function and in return, this ...


2 Answers

Alternatively, with strsplit:

x <- as.character(4321)
as.numeric(unlist(strsplit(x, "")))
[1] 4 3 2 1
like image 61
blmoore Avatar answered Sep 20 '22 21:09

blmoore


Use substring to extract character at each index and then convert it back to integer:

x <- 4321
as.integer(substring(x, seq(nchar(x)), seq(nchar(x))))
[1] 4 3 2 1
like image 40
Arun Avatar answered Sep 20 '22 21:09

Arun