[英]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.