简体   繁体   English

R:仅用数字(1、2 等)替换字符序数(第一、第二等)

[英]R: Replace character ordinal numbers (first, second, etc.) with just the number (1, 2, etc.)

I have some strings of addresses with character ordinal numbers (first, second and so on).我有一些带有字符序数(第一、第二等)的地址字符串。

x <- "first bank street" x <- “第一条银行街”

Output needed需要输出

"1 bank street" “1 条银行街”

Any help would be appreciated.任何帮助,将不胜感激。

Just write a helper function to do it for you - although I guess it depends on how high the numbers go.只需编写一个辅助函数来为您执行此操作-尽管我想这取决于数字的大小。 If it's only 1 to 10 then it's easy.如果它只是 1 到 10,那么这很容易。

There's no doubt a more elegant way to do this, but this will for sure solve your basic issue.毫无疑问,这是一种更优雅的方法,但这肯定会解决您的基本问题。

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)

  }

Then you can test it:然后你可以测试一下:

x1 <- 'first bank street'

address_string_replace(x1) #returns '1 bank street'

x2 <- 'second port avenue'

address_string_replace(x2) #returns '2 port avenue'

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 使用混合值(字符串,日期,数字等)在数据框中舍入数字 - Rounding numbers in a dataframe with mixed values (string, date, number, etc.) 将千字节,兆字节等转换为R中的字节 - Converting kilobytes, megabytes etc. to bytes in R 如何使用 R 从字符串中间删除两位数字(01、02 等)的前导零? - How can I remove leading zeros for two digits number (01, 02, etc.) from the middle of character string using R? 正则表达式,匹配一对单词的第一次、第二次、第三次等出现 - Regular expression, match between the first, second, third etc. occurences of a pair of words 将R中的时间数据绘制成各种分辨率(分钟,小时,秒等) - Plot time data in R to various resolutions (to the minute, to the hour, to the second, etc.) 您如何编写包装函数或类来将数字格式化为R中的百分比,货币等? - How would you write a wrapper function or class to format numbers as percent, currency, etc. in R? 将which.max应用于第二,第三等最高值 - apply which.max to second, third, etc. highest value 用列折叠行数据(字符、数字、因子等) - Collapsing Row Data with Columns (character, numeric, factors, etc.) 如何有效地从 R 到 CSV 到 HTML 截断(ö、é 等)? - How to truncate (ö, é etc.) efficiently from R to CSV to HTML? R中的封闭环境,功能环境等不同 - Distinct enclosing environment, function environment, etc. in R
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM