r - 如何将 R 中的字符串中的连续整数组合在一起?

标签 r string

假设我有这个字符串

x <- "1:A 2:A 3:A 5:A 7:A 8:A 9:A"

R 中是否有一个函数允许我准备这个字符串的各个部分以便输出:

[1] 1-3:A 5:A 7-9:A

最佳答案

#Get the numeric values only
temp = as.integer(unlist(strsplit(gsub(":A", "", x), " ")))

#Split temp into chunks of consecutive integers
#Get range for each chunk and paste them together
#Paste :A at the end
sapply(split(temp, cumsum(c(TRUE, diff(temp) != 1))), function(x)
    paste(paste(unique(range(x)), collapse = "-"), ":A", sep = ""))
#      1       2       3 
#"1-3:A"   "5:A" "7-9:A" 

关于r - 如何将 R 中的字符串中的连续整数组合在一起?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44788101/

相关文章:

regex - 循环将十进制逗号 (,) 转换为点 (.) 以更改 data.frame 列的类

r - fread 中的错误(showProgress 不是整数类型,而是类型 'logical'。请报告。)

java - 声明一个字符串数组

R bookdown - 表头中的数学不起作用

RStudio 已损坏,无法在 MacOS High Sierra(版本 10.13.6)上打开

r - 将有关轴上变量的更多信息合并到 ggplot 中的热图中

c++ - 将 std::string 中的十六进制值存储在 std::vector 中,反之亦然?

c# - 如何检查两个字符串是否匹配或在 C# 中是否为空

string - 为什么我的代码在我的字符串后打印一个重复的垃圾字符?

c++ - 如何正确初始化宽字符串?