是否有内置方法将序数转换为数字向量?ordinal <- c(\'First\', \'Third\', \'Second\')ordinal_to_numeric(ordinal)#[1] 1 3 2ordinal2 <...
是否有内置方法将序数转换为数字向量?
ordinal <- c("First", "Third", "Second")
ordinal_to_numeric(ordinal)
#[1] 1 3 2
ordinal2 <- c("1st", "4th", "2nd")
ordinal_to_numeric(ordinal)
#[1] 1 4 2
人们确实可以创建一本字典,但这很容易变得麻烦。
我迟到了,@DaveArmstrong 的解决方案肯定更简单,但这里有一个更通用的解决方案,首先将序数转换为基数,然后将它们传递 nombre::uncardinal()
给转换为数字。 str_replace_all()
序数 -> 基数转换的向量基于 源 代码 nombre::ordinal()
.
library(stringr)
library(nombre)
ordinal_to_numeric <- function(x) {
w_word_stem <- function(x) {
x |>
str_to_lower() |>
str_remove("st$|nd$|rd$|th$") |>
str_replace_all(c(
"fir$" = "one",
"seco$" = "two",
"thi$" = "three",
"f$" = "ve",
"eigh$" = "eight",
"nin$" = "nine",
"ie$" = "y"
)) |>
uncardinal()
}
w_num_stem <- function(x) {
x |>
str_extract("^-?\\d+") |>
as.numeric()
}
out <- suppressWarnings(ifelse(
str_starts(x, "-?\\d"),
w_num_stem(x),
w_word_stem(x)
))
if (any(is.na(out) & !is.na(x))) {
warning("Conversion failed for some inputs")
}
out
}
ordinal <- c("First", "Third", "Second", "Five Hundred Thirty Eighth", "Negative Twenty-Third")
ordinal_to_numeric(ordinal)
# 1 3 2 538 -23
ordinal2 <- c("1st", "4th", "2nd", "538th", "-23rd")
ordinal_to_numeric(ordinal2)
# 1 4 2 538 -23