如何扩展给定的数字范围以包括所有通过破折号分隔的数字



我正在尝试扩展当前由破折号分隔的数字,以包括所有数字。

好消息是我找到了有助于以下配置的代码(不是我的(:

"宴会厅1-3"产生"宴会厅1,宴会厅2,宴会厅3",这是我想要的。问题在于,这是有条件的,这是在破折号之前和之后没有空格。目前,"宴会厅1-3"回归"宴会厅1 -3,宴会厅1-3,宴会厅1-3";这不是所需的输出。

请注意,由于几个原因,必须保留破折号之前和之后的空间。"宴会厅1-3"的输入必须保持不变。

## Dealing with Dash Seperated Sequences of Numbers
expand.dash <- function(dashed) {
  limits <- as.numeric(unlist(strsplit(dashed, '-')))
  seq(limits[1], limits[2])
}

expand.ballrooms <- function(txt) {
   str <- gsub('\d+-\d+', '%d', txt)
  dashed_str <- gsub('[a-zA-Z ]+', '', txt)
  sprintf(str, expand.dash(dashed_str))
}
expand.ballrooms("Ballroom 1-3")  
# this works but the line below fails to output the desired result 
expand.ballrooms("Ballroom 1 - 3")
# Result should be identical to the the output returned by the previous line. 

虽然没有弹出错误消息,但破折号之前和之后的空间使输出仅重复。

expand.ballrooms中更改此

gsub('\d+-\d+', '%d', txt)

gsub('\d+\s*-\s*\d+', '%d', txt)

您可以在函数 expand.ballrooms

中的 gsub中的图案中添加可选的空格
gsub('\d+\s?-\s?\d+', '%d', txt)

修改的功能将为

expand.dash <- function(dashed) {
  limits <- as.numeric(unlist(strsplit(dashed, '-')))
  seq(limits[1], limits[2])
}

expand.ballrooms <- function(txt) {
  str <- gsub('\d+\s?-\s?\d+', '%d', txt)
  dashed_str <- gsub('[a-zA-Z ]+', '', txt)
  sprintf(str, expand.dash(dashed_str))
}

现在,这将适用于两种情况

expand.ballrooms("Ballroom 1-3")
#[1] "Ballroom 1" "Ballroom 2" "Ballroom 3"
expand.ballrooms("Ballroom 1 - 3")
#[1] "Ballroom 1" "Ballroom 2" "Ballroom 3"

相关内容

最新更新