How to extract a number by digits using R?

Suppose I have a number: 4321

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

How should I do it?

+4
source share
4 answers

Alternatively, with strsplit :

 x <- as.character(4321) as.numeric(unlist(strsplit(x, ""))) [1] 4 3 2 1 
+8
source

Use substring to extract a character at each index, and then convert it to an integer:

 x <- 4321 as.integer(substring(x, seq(nchar(x)), seq(nchar(x)))) [1] 4 3 2 1 
+4
source

For real fun, here's an absurd method:

 digspl<-function(x){ x<-trunc(x) # justin case mj<-trunc(log10(x)) y <- trunc(x/10^mj) for(j in 1:mj) { y[j+1]<- trunc((xy[j]*10^(mj-j+1))/(10^(mj-j))) x<- x - y[j]*10^(mj-j+1) } return(y) } 
+4
source

For fun here is an alternative:

 x <- 4321 read.fwf(textConnection(as.character(x)), rep(1, nchar(x))) # V1 V2 V3 V4 # 1 4 3 2 1 

The only advantage I can think of is the possibility of exploding your input in different widths, although, I think, you can do this with a substring as well.

+1
source

Source: https://habr.com/ru/post/1498948/


All Articles