【问题标题】:R: Replace character ordinal numbers (first, second, etc.) with just the number (1, 2, etc.)R:仅用数字(1、2等)替换字符序数(第一、第二等)
【发布时间】:2018-10-08 07:47:05
【问题描述】:

我有一些带有字符序号的地址字符串(第一、第二等等)。

x

需要输出

“1 银行街”

任何帮助将不胜感激。

【问题讨论】:

  • 这不是一个纯粹的正则表达式任务;正则表达式不能“知道”first 应该变成1。您必须编写一些逻辑来映射值。
  • 我认为你应该写一本像{'first': 1, 'second': 2}这样的字典。也许你可以找到准备好的。

标签: r gsub stringr


【解决方案1】:

只需编写一个辅助函数来为您完成 - 虽然我猜这取决于数字有多高。如果只有 1 到 10,那很容易。

毫无疑问,这是一种更优雅的方法,但这肯定会解决您的基本问题。

address_string_replace <- function(x) {

  require(tidyverse)

  address_tbl <- tibble(number = 1:10,
                    text = c('first','second','third','fourth','fifth','sixth','seventh','eighth','ninth','tenth'))

  address_test <- 1:nrow(address_tbl)  

  tested_value <- tibble()

  for (i in address_test) {

    new_test <- tibble(test = ifelse(str_detect(x,address_tbl$text[i])==TRUE,address_test[i],0))

    tested_value <- bind_rows(tested_value,new_test)

  }

  tested_value <- tested_value %>%
    filter(!test == 0)

  value <- tested_value[['test']]

  address_fix <- address_tbl %>%
    filter(number == value)

  new_x <- gsub(address_fix$text,address_fix$number,x)

  return(new_x)

  }

那你就可以测试了:

x1 <- 'first bank street'

address_string_replace(x1) #returns '1 bank street'

x2 <- 'second port avenue'

address_string_replace(x2) #returns '2 port avenue'

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-12-17
    • 1970-01-01
    • 2014-03-07
    • 1970-01-01
    • 1970-01-01
    • 2018-10-18
    相关资源
    最近更新 更多