8

假设我有一个号码:4321

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

我该怎么做呢?

4

5 回答 5

11

或者,使用strsplit

x <- as.character(4321)
as.numeric(unlist(strsplit(x, "")))
[1] 4 3 2 1
于 2013-08-26T11:47:16.357 回答
6

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

x <- 4321
as.integer(substring(x, seq(nchar(x)), seq(nchar(x))))
[1] 4 3 2 1
于 2013-08-26T11:40:20.687 回答
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)
}
于 2013-08-26T14:32:47.177 回答
1

为了好玩,这里有一个替代方案:

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

我能想到的唯一优点是可以将您的输入分解为不同的宽度,尽管我想您也可以使用子字符串来做到这一点。

于 2013-08-26T13:05:49.197 回答
0

另一种解决方案,使用模运算符:

get_digit <- function(x, d) {
    # digits from the right
    # i.e.: first digit is the ones, second is the tens, etc.
    (x %% 10^d) %/% (10^(d-1))
}

# for one number
get_all_digit <- function(x) {
    get_digit_x <- function(d) get_digit(x,d)
    sapply(nchar(x):1, get_digit_x) 
}

# for a vector of numbers
digits <- function(x) {
    out <- lapply(x, get_all_digit)
    names(out) <- x
    out
}

例子:

> digits(100:104)
$`100`
[1] 1 0 0

$`101`
[1] 1 0 1

$`102`
[1] 1 0 2

$`103`
[1] 1 0 3

$`104`
[1] 1 0 4
于 2018-11-07T05:51:06.367 回答