如何使用R将数字提取为数字?

use*_*901 7 numbers r extract digits

假设我有一个数字:4321

我想把它提取成数字:4,3,2,1

我该怎么做呢?

blm*_*ore 10

或者,用strsplit:

x <- as.character(4321)
as.numeric(unlist(strsplit(x, "")))
[1] 4 3 2 1
Run Code Online (Sandbox Code Playgroud)


Aru*_*run 5

使用substring来提取字符每个索引处,然后将其转换回整数:

x <- 4321
as.integer(substring(x, seq(nchar(x)), seq(nchar(x))))
[1] 4 3 2 1
Run Code Online (Sandbox Code Playgroud)


Car*_*oft 5

为了真正的乐趣,这是一个荒谬的方法:

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((x-y[j]*10^(mj-j+1))/(10^(mj-j)))
    x<-  x - y[j]*10^(mj-j+1)
    }
    return(y)
}
Run Code Online (Sandbox Code Playgroud)