R 如何将给定的数字范围扩展到包含由破折号分隔的所有数字
我正在尝试扩展一个由破折号分隔的数字范围,以包括所有数字 好消息是,我找到了有助于以下配置的代码(不是我的代码): “舞厅1-3”产生“舞厅1,舞厅2,舞厅3”,这就是我想要的。问题是,这是以破折号前后没有空格为条件的。目前,“舞厅1-3”返回“舞厅1-3、舞厅1-3、舞厅1-3”;这不是期望的输出 请注意,由于几个原因,必须保留破折号前后的空格。“舞厅1-3”的输入必须保持不变R 如何将给定的数字范围扩展到包含由破折号分隔的所有数字,r,R,我正在尝试扩展一个由破折号分隔的数字范围,以包括所有数字 好消息是,我找到了有助于以下配置的代码(不是我的代码): “舞厅1-3”产生“舞厅1,舞厅2,舞厅3”,这就是我想要的。问题是,这是以破折号前后没有空格为条件的。目前,“舞厅1-3”返回“舞厅1-3、舞厅1-3、舞厅1-3”;这不是期望的输出 请注意,由于几个原因,必须保留破折号前后的空格。“舞厅1-3”的输入必须保持不变 ## Dealing with Dash Seperated Sequences of Numbers expan
## 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.dash您可以在函数
expand.ballrooms
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))
}
在
中展开.舞厅
更改此项
gsub('\\d+-\\d+','%d',txt)
为此:
gsub('\\d+\\s*-\\s*\\d+','%d',txt)
感谢您的详细介绍
expand.ballrooms("Ballroom 1-3")
#[1] "Ballroom 1" "Ballroom 2" "Ballroom 3"
expand.ballrooms("Ballroom 1 - 3")
#[1] "Ballroom 1" "Ballroom 2" "Ballroom 3"